package jsyf.oa.service.contract;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.constant.SendConstant;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.attach.AttachDao;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.contract.*;
import jsyf.oa.dao.device.DeviceDisplaceDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.dao.weekplan.WeekPlanDao;
import jsyf.oa.dao.wreport.WReportCustomerDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.contract.*;
import jsyf.oa.entity.device.DeviceDisplaceEntity;
import jsyf.oa.entity.system.*;
import jsyf.oa.entity.wreport.WReportCustomerEntity;
import jsyf.oa.facade.contract.ContractMainFacade;
import jsyf.oa.ientity.IBaseEntity;
import jsyf.oa.service.wechat.service_company.HttpUtil;
import net.sf.json.JSONArray;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;


@SuppressWarnings("all")
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ContractMainService implements ContractMainFacade {
    @Autowired
    private ContractMainDao contractMainDao;
    @Autowired
    private ContractSalesDao contractSalesDao;
    @Autowired
    private GuarantorDao guarantorDao;
    @Autowired
    private RepaymentDao repaymentDao;
    @Autowired
    private ReplacementDao replacementDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private CopierDao copierDao;
    @Autowired
    private ContractTermsDao contractTermsDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private DeviceDisplaceDao deviceDisplaceDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private FinancingDao financingDao;
    @Autowired
    private AttachDao attachDao;
    @Autowired
    private ContractHistoryDao contractHistoryDao;
    @Autowired
    private CollectionDao collectionDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private WeekPlanDao weekPlanDao;
    @Autowired
    private AvailableDao availableDao;
    @Autowired
    private WReportCustomerDao wReportCustomerDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private OverDueDetailDao overDueDetailDao;
    @Autowired
    private RegionAchivementsDao regionAchivementsDao;
    //默认合同条款数
    private Integer contractTermsNumber = 3;
    //默认已有的合同条款数木
    private final Integer haveTermsNumber = 10;


    private static Boolean flag = true;
    private final static String DATEHOURFORMAT = "HH:mm";


    @Override
    public JSONObject selectMainList(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String createUserName = json.getString("createUserName");
        String auditFlag = json.getString("auditFlag");
        String outBoundType = json.getString("outBoundType");
        String haveDelivery = json.getString("haveDelivery");
        String serialNo = json.getString("serialNo");
        String buyer = json.getString("customerKey");
        String companyId = json.getString("companyId");
        String userId = json.getString("userId");
        String contractNo = json.getString("contractNo");
        String modelName = json.getString("modelName");
        String brandName = json.getString("brandName");
        String key = json.getString("key");
        String newOrOld = json.getString("newOrOld");//新机--旧机

        StringBuilder condition = new StringBuilder();
        String companyIds = "";
        String userIds = "";
        if (!StringUtils.isBlank(userId)) {
            userIds = checkDao.getChilderByUserId(userId, true);
            List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String selectCompanyId = userList.get(i).getString("companyId");
                    String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                    //如果有下级
                    if (!StringUtils.isBlank(ids)) {
                        //如果有多个下级
                        if (ids.indexOf(",") >= 0) {
                            String[] idsSplit = ids.split(",");
                            for (String id : idsSplit) {
                                companyIds += "'" + id + "',";
                            }
                        } else {
                            //如果只有一个下级
                            companyIds += "'" + ids + "',";
                        }
                    }
                    companyIds += "'" + selectCompanyId + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            } else {
                companyIds = "''";
            }
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(json.getString("pageSize"))) {
            pageSize = json.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(json.getString("requestPage"))) {
            requestPage = json.getInteger("requestPage");
        }
        if (!StringUtils.isBlank(createUserName)) {
            condition.append(" AND t_con_main.create_User_Name LIKE '%" + createUserName + "%'");
        }
        if (!StringUtils.isBlank(buyer)) {
            condition.append(" AND t_con_main.buyer LIKE '%" + buyer + "%'");
        }
        if (!StringUtils.isBlank(serialNo)) {
            condition.append(" and t_con_main.SERIAL_NO like '%" + serialNo + "%'");
        }
        if (!StringUtils.isBlank(auditFlag)) {
            condition.append("AND t_con_main.AUDIT_FLAG='" + auditFlag + "'");
        }
        if (!StringUtils.isBlank(companyId)) {
            condition.append("AND t_con_main.SELLER_COMPANY_ID='" + companyId + "'");
        }
        if (!StringUtils.isBlank(outBoundType)) {
            condition.append("AND t_dvc_outbound.TYPE ='" + outBoundType + "'");
        }
        if (!StringUtils.isBlank(haveDelivery)) {
            condition.append("AND t_con_main.HAVE_DELIVERY ='" + haveDelivery + "'");
        }
        if (!StringUtils.isBlank(contractNo)) {
            condition.append("AND t_con_main.CONTRACT_NO='" + contractNo + "'");
        }
        if (!StringUtils.isBlank(modelName)) {
            condition.append("AND t_con_main.MODEL_NAME like '%" + modelName + "%'");
        }
        if (!StringUtils.isBlank(brandName)) {
            if (!"品牌".equals(brandName)) {
                condition.append("AND t_con_main.BRAND_NAME='" + brandName + "'");
            }
        }
        if (!StringUtils.isBlank(key)) {
            condition.append("AND (t_con_main.CONTRACT_NO like '%" + key + "%'");
            condition.append("OR t_con_main.MODEL_NAME like '%" + key + "%'");
            condition.append("OR t_con_main.SELLER like '%" + key + "%'");
            condition.append("OR t_con_main.SERIAL_NO like '%" + key + "%'");
            condition.append("OR t_con_main.buyer like '%" + key + "%'");
            condition.append("OR t_con_main.region_Manager_Name like '%" + key + "%'");
            condition.append("OR t_con_main.DEVICE_TYPE like '%" + key + "%'");
            condition.append("OR t_con_main.BRAND_NAME like '%" + key + "%'");
            condition.append("OR t_con_main.buy_type like '%" + key + "%'");
            condition.append("OR t_con_main.create_User_Name like '%" + key + "%'");
            condition.append(")");
        }
        if (!StringUtils.isBlank(newOrOld)) {//新机X--旧机J
            if ("J".equals(newOrOld)) {
                condition.append(" AND t_con_main.CONTRACT_TYPE=2\n");
            } else {
                condition.append(" AND t_con_main.CONTRACT_TYPE=1\n");
            }
        }

        List<JSONObject> recordsList = contractMainDao.selectByUserId(userId, condition.toString(), companyIds, userIds, requestPage, pageSize);
        int recordCount = contractMainDao.selectByUserId(userId, condition.toString(), companyIds, userIds, 1, Integer.MAX_VALUE).size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", recordsList);
        return result;
    }

    @Override
    public JSONObject save(String jsonData) {
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//买卖双方及担保方信息
        ContractSalesEntity contractSalesEntity = model.getSales();//产品及付款条款
        ReplacementEntity replacementEntity = model.getReplacement();//旧机置换
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资

        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资打包
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        List<RepaymentEntity> repaymentFQFirstList = model.getRepaymentFQFirstList();//分期首付款信息

        List<GuarantorEntity> guarantorList = model.getGuarantorList();//担保人
        List<ContractTermsEntity> contractTermsEntityList = model.getContractTermsList();//合同条款
        String mainId = contractMainEntity.getId();//主表的ID
        //修改合同，先级联删除现有的所有合同，再添加
        guarantorDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        repaymentDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        contractSalesDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        contractTermsDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        if (!contractMainEntity.getAuditFlag().equals("1")) {
            //删除现有的审核人和抄送人
            auditDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='contractType' ", new String[]{mainId});
            copierDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='contractType' ", new String[]{mainId});
            //创建新的客户实体
            WReportCustomerEntity newWReportCustomerEntity = new WReportCustomerEntity();
            WReportCustomerEntity oldWReportCustomerEntity = wReportCustomerDao.getByTel(contractMainEntity.getBuyerTel());
            if (null == oldWReportCustomerEntity) {
                //修改客户类型
                if (matchesCard(contractMainEntity.getBuyerTaxNo())) {
                    newWReportCustomerEntity.setCustomerType("客户(个人)");
                    contractMainEntity.setActualCarBuyer(contractMainEntity.getBuyer());
                    contractMainEntity.setActualCarBuyerTel(contractMainEntity.getBuyerTel());
                    contractMainEntity.setBuyerType(0);
                } else {
                    newWReportCustomerEntity.setCustomerType("客户(企业)");
                    contractMainEntity.setLegalRepresentativeName(contractMainEntity.getBuyer());
                    contractMainEntity.setLegalRepresentativeTel(contractMainEntity.getBuyerTel());
                    contractMainEntity.setBuyerType(1);
                }
                newWReportCustomerEntity.setBuyType(contractMainEntity.getBuyType());
                newWReportCustomerEntity.setName(contractMainEntity.getBuyer());
                newWReportCustomerEntity.setCreateUserId(contractMainEntity.getRegionManagerId());
                newWReportCustomerEntity.setCreateTime(wReportCustomerDao.getCurrentTime());
                newWReportCustomerEntity.setTel(contractMainEntity.getBuyerTel());
                newWReportCustomerEntity.setCustomerAddress(contractMainEntity.getBuyerAddress());
                newWReportCustomerEntity.setIdCard(contractMainEntity.getBuyerTaxNo());
                wReportCustomerDao.add(newWReportCustomerEntity);
            } else {
                //修改客户类型
                if (matchesCard(contractMainEntity.getBuyerTaxNo())) {
                    oldWReportCustomerEntity.setCustomerType("客户(个人)");
                    contractMainEntity.setActualCarBuyer(contractMainEntity.getBuyer());
                    contractMainEntity.setActualCarBuyerTel(contractMainEntity.getBuyerTel());
                } else {
                    oldWReportCustomerEntity.setCustomerType("客户(企业)");
                    contractMainEntity.setLegalRepresentativeName(contractMainEntity.getBuyer());
                    contractMainEntity.setLegalRepresentativeTel(contractMainEntity.getBuyerTel());
                }
                oldWReportCustomerEntity.setIdCard(contractMainEntity.getBuyerTaxNo());
                oldWReportCustomerEntity.setBuyType(contractMainEntity.getBuyType());
                oldWReportCustomerEntity.setName(contractMainEntity.getBuyer());
                oldWReportCustomerEntity.setTel(contractMainEntity.getBuyerTel());
                oldWReportCustomerEntity.setCustomerAddress(contractMainEntity.getBuyerAddress());
                oldWReportCustomerEntity.setIdCard(contractMainEntity.getBuyerTaxNo());
                wReportCustomerDao.update(oldWReportCustomerEntity);
            }

            //获取区域经理信息
            String userId = contractMainEntity.getRegionManagerId();
            UserEntity userEntity = userDao.getById(userId);
            if (userEntity.getJobState() != 1) {
                //获取能看到他的人
                String userIds = checkDao.getParentByUserId(userId, true);//能看到他的上级人员

                //获取区域信息
                List<JSONObject> jsonObject = contractMainDao.getRegionNameByUserId(userId);
                if (jsonObject.size() > 0) {
                    contractMainEntity.setRegionName(jsonObject.get(0).getString("regionName"));
                    contractMainEntity.setRegionId(jsonObject.get(0).getString("regionId"));
                }
                //获取数据专员
                jsonObject = userDao.getUserByUserIdAndRoleName(userId, "数据专员");
                if (jsonObject.size() > 0) {
                    contractMainEntity.setDataOfficerName(jsonObject.get(0).getString("userName"));
                    contractMainEntity.setDataOfficerId(jsonObject.get(0).getString("userId"));
                }
                //债权经理
                jsonObject = userDao.getUserByUserIdAndRoleName(userId, "债权经理");
                if (jsonObject.size() > 0) {
                    contractMainEntity.setCreditManagerName(jsonObject.get(0).getString("userName"));
                    contractMainEntity.setCreditManagerId(jsonObject.get(0).getString("userId"));
                }
                //获取区域经理的大区经理，区域总监，销售总监，总经理
                String BigRegionId = contractMainEntity.getRegionId();
                String managerCompanyId = contractMainEntity.getSellerCompanyId();
                //分别获取大区经理，区域总监，销售总监，总经理
                List<JSONObject> josnDq = regionAchivementsDao.getAllParent(BigRegionId, managerCompanyId, "大区经理");
                List<JSONObject> josnQu = regionAchivementsDao.getAllParent(BigRegionId, managerCompanyId, "区域总监");
                List<JSONObject> josnXs = regionAchivementsDao.getAllParent(BigRegionId, managerCompanyId, "销售总监");
                List<JSONObject> josnzjl = regionAchivementsDao.getAllParent(BigRegionId, managerCompanyId, "总经理");
                JSONObject managerInfo = null;
                if (josnDq.size() > 0) {
                    contractMainEntity.setBigRegionManagerId(josnDq.get(0).getString("userId"));
                    contractMainEntity.setBigRegionManagerName(josnDq.get(0).getString("userName"));
                }
                if (josnQu.size() > 0) {
                    managerInfo = this.getAllManagerId(josnQu, managerCompanyId, "区域总监");
                    contractMainEntity.setRegionDirectorId(managerInfo.getString("managerId"));
                    contractMainEntity.setRegionDirectorName(managerInfo.getString("managerName"));
                }
                if (josnXs.size() > 0) {
                    managerInfo = this.getAllManagerId(josnXs, managerCompanyId, "销售总监");
                    contractMainEntity.setDirectorOfSalesId(managerInfo.getString("managerId"));
                    contractMainEntity.setDirectorOfSalesName(managerInfo.getString("managerName"));
                }
                if (josnzjl.size() > 0) {
                    managerInfo = this.getAllManagerId(josnzjl, managerCompanyId, "总经理");
                    contractMainEntity.setGeneralManagerId(managerInfo.getString("managerId"));
                    contractMainEntity.setGeneralManagerName(managerInfo.getString("managerName"));
                }
            }
            //获取销售价格
            contractMainEntity.setSalesPrice(contractSalesEntity.getUnitPrice());
            //临时处理，合同编号手填
            //contractMainEntity.setContractNo("-");
            //contractMainEntity.setHaveDelivery(0);
        }
        //曹国玉特殊处理
        if (contractMainEntity.getCreateUserId().equals("201711271733404C9DA1461F2421F828") && contractMainEntity.getAuditFlag().equals("0")) {
            contractMainEntity.setAuditFlag("1");
            contractMainEntity.setCurrentAuditorId("201711271733404C9DA1461F2421F828");
            contractMainEntity.setCurrentAuditorName("曹国玉");
            //曹国玉直接审核通过，带出合同编号
            contractMainEntity.setContractNo(createContractNo(contractMainEntity));
        }
        //合同机型大写
        contractMainEntity.setModelName(contractMainEntity.getModelName().toUpperCase());
        if (contractMainEntity.getAuditFlag().equals("1")) {
            //应收台账(区域经理、大区经理、区域支持、接管区域经理)离职发消息给数据专员
            sendResignationMessage(contractMainEntity, jsonObjectList);
        }
        if (!StringUtils.isBlank(mainId)) {//修改
            contractMainEntity.setCreateTime(((ContractMainEntity) contractMainDao.getIBaseEntityById(mainId)).getCreateTime());
            contractMainDao.update(contractMainEntity);
        } else {//新增
            //若果是新增。需要自动创建合同号
            //contractMainEntity.setContractNo(createContractNo(contractMainEntity));
            contractMainEntity.setHaveDelivery(0);
            contractMainDao.add(contractMainEntity);
        }
        mainId = contractMainEntity.getId();
        //曹国玉特殊处理
        if (contractMainEntity.getCreateUserId().equals("201711271733404C9DA1461F2421F828") && contractMainEntity.getAuditFlag().equals("1")) {
            //删除现有的抄送人
            List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object) copierDao.getIBaseEntityByCondition(" AND MAIN_ID=? and module_name='contractType'", new Object[]{mainId});
            if (null == auditEntityList || auditEntityList.size() <= 0) {
                JSONObject auditAndcoiper = getJSONByAuditAndCopier(contractMainEntity.getCreateUserId(), mainId, contractMainEntity.getAuditFlag(), contractMainEntity.getRegionManagerId());
            }
        }
        if (!contractMainEntity.getAuditFlag().equals("1")) {
            //获取审核人
            List<AuditEntity> auditors = model.getAuditors();
            //获取抄送人
            List<CopierEntity> copiers = model.getCopiers();
            //添加审核人
            if (null != auditors && auditors.size() > 0) {
                for (int i = 0; i < auditors.size(); i++) {
                    AuditEntity auditEntity = new AuditEntity();
                    auditEntity.setAuditorId(auditors.get(i).getAuditorId() != null ? auditors.get(i).getAuditorId() : auditors.get(i).getUserId());
                    auditEntity.setAuditorName(auditors.get(i).getAuditorName());
                    auditEntity.setRoleName(auditors.get(i).getRoleName());
                    auditEntity.setAuditSort(i);
                    if (i == 0 && !contractMainEntity.getAuditFlag().equals("-1")) {
                        //设置第一审核人状态
                        auditEntity.setAuditFlag(0);
                        contractMainEntity.setCurrentAuditorName(auditEntity.getAuditorName());
                        contractMainEntity.setCurrentAuditorId(auditEntity.getAuditorId());
                        if (contractMainEntity.getAuditFlag().equals("0")) {
                            //企业号:给审核人发送消息
                            JSONObject msgObject = new JSONObject();
                            msgObject.put("userIds", auditEntity.getAuditorId());
                            msgObject.put("content", String.format(CONTRACT_AUDIT_AUDIT,
                                    auditEntity.getAuditorName(),
                                    contractMainEntity.getModelName(),
                                    contractMainEntity.getSalesPrice(),
                                    contractMainEntity.getCreateUserName(),
                                    DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                            //标记以前的审核人、申请人消息为已读
                            messageReceiverRead(mainId, 0);
                            messageReceiverRead(mainId, 2);

                            //保存消息到消息表t_sys_message
                            MessageEntity messageEntity = new MessageEntity();
                            messageEntity.setCreateUserId(contractMainEntity.getCreateUserId());
                            messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                            messageEntity.setContent(String.format(CONTRACT_AUDIT_AUDIT,
                                    auditEntity.getAuditorName(),
                                    contractMainEntity.getModelName(),
                                    contractMainEntity.getSalesPrice(),
                                    contractMainEntity.getCreateUserName(),
                                    DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                            messageEntity.setMessageType(0);
                            messageEntity.setMainId(mainId);
                            messageEntity.setDelFlag(0);
                            messageEntity.setOpenUrl("/page/apply/contract/detail_new.html?id=" + mainId + "&pageType=look&openType=dialog");
                            messageEntity.setOpenTitle(String.format(CONTRACT_AUDIT_AUDIT_MESSAGE, contractMainEntity.getCreateUserName()));
                            messageDao.add(messageEntity);

                            //保存消息到消息收件人表t_sys_message_receiver
                            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                            messageReceiverEntity.setMessageId(messageEntity.getId());
                            messageReceiverEntity.setUserId(auditEntity.getAuditorId());
                            messageReceiverEntity.setUserType(0);
                            messageReceiverEntity.setReadFlag(0);
                            messageReceiverDao.add(messageReceiverEntity);

                            //发消息
                            jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                        }
                    } else {
                        auditEntity.setAuditFlag(-1);
                    }
                    auditEntity.setModuleName("contractType");//合同类型
                    auditEntity.setMainId(mainId);
                    auditDao.add(auditEntity);
                }
            }
            //添加抄送人
            if (null != copiers && copiers.size() > 0) {
                for (int i = 0; i < copiers.size(); i++) {
                    CopierEntity copierEntity = new CopierEntity();
                    copierEntity.setCopierId(copiers.get(i).getCopierId() != null ? copiers.get(i).getCopierId() : copiers.get(i).getUserId());
                    copierEntity.setCopierName(copiers.get(i).getCopierName());
                    copierEntity.setModuleName("contractType");//合同类型
                    copierEntity.setMainId(mainId);
                    copierDao.add(copierEntity);
                }
            }
        }
        //更新主表信息
        ContractMainEntity mainEntitys = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (mainEntitys.getHaveOverdue() != 2) {
            contractMainEntity.setHaveOverdue(0);
            contractMainEntity.setHaveOverdueNo(-6);
            contractMainDao.update(contractMainEntity);
        }
        //添加--产品及付款条款
        contractSalesEntity.setMainId(mainId);
        //单价==总价
        contractSalesEntity.setTotalPrice(contractSalesEntity.getUnitPrice());
        if ("内部分期".equalsIgnoreCase(contractMainEntity.getBuyType())) {
            contractSalesEntity.setFirstPayment(contractMainEntity.getFqFirstMoney());
        }
        contractSalesEntity.setUpdateUserId(contractMainEntity.getUpdateUserId());
        contractSalesDao.add(contractSalesEntity);
        //添加担保人信息
        if (null != guarantorList) {
            for (int i = 0; i < guarantorList.size(); i++) {
                if (!StringUtils.isBlank(guarantorList.get(i).getGuarantor())) {
                    guarantorList.get(i).setMainId(mainId);
                    guarantorList.get(i).setSortNo(i);
                    guarantorList.get(i).setLogFlag(0);
                    guarantorDao.add(guarantorList.get(i));
                }
            }
        }
        //首付款信息(销售台账)
        if (null != repaymentaSFEntityList && repaymentaSFEntityList.size() > 0) {
            for (int i = 0; i < repaymentaSFEntityList.size(); i++) {

                RepaymentEntity repaymentEntity = repaymentaSFEntityList.get(i);
                //还款日期不为空则添加
                //模块0-内部分期/1-垫款/2-融资分期/3-首付款信息
                repaymentaSFEntityList.get(i).setType(3);
                repaymentaSFEntityList.get(i).setMainId(mainId);
                repaymentaSFEntityList.get(i).setSortNo(i);
           /*     if (contractMainEntity.getBuyType().equals("内部分期")) {
                    repaymentaSFEntityList.get(i).setTotal(contractMainEntity.getFqFirstMoney().subtract(contractMainEntity.getDkFirstMoney()));
                } else if (contractMainEntity.getBuyType().equals("融资租赁")) {
                    repaymentaSFEntityList.get(i).setTotal(contractSalesEntity.getFirstPayment().subtract(contractMainEntity.getDkFirstMoney()));
                } else {
                    repaymentaSFEntityList.get(i).setTotal(contractSalesEntity.getTotalPrice().subtract(contractMainEntity.getDkFirstMoney()));
                }*/
                repaymentDao.add(repaymentaSFEntityList.get(i));
            }
        }
        //判断是否为垫款->插入分期表
        if (contractMainEntity.getHaveRepayment() == 1) {
            for (int i = 0; i < repaymentaDKEntityList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentaDKEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setType(1);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentEntity.getInterest().add(repaymentEntity.getPrincipal()));
                    repaymentDao.add(repaymentEntity);
                }
            }
        }
        //判断购买方式是否为内部分期->插入分期表
        if (contractMainEntity.getBuyType().equals("内部分期")) {
            for (int i = 0; i < repaymentaFQEntityList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentaFQEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(0);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentaFQEntityList.get(i).getInterest().add(repaymentaFQEntityList.get(i).getPrincipal()));
                    repaymentDao.add(repaymentEntity);

                }
            }
        }
        //判断购买方式是否为内部分期 并且有分期首付款分期 ->插入分期表
        if (contractMainEntity.getBuyType().equals("内部分期") && contractMainEntity.getHaveFQFirst() == 1) {
            for (int i = 0; i < repaymentFQFirstList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentFQFirstList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(5);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentFQFirstList.get(i).getPrincipal());
                    repaymentDao.add(repaymentEntity);
                }
            }
        }
        //判断购买方式是否为融资租赁->插入分期表
        if (contractMainEntity.getBuyType().equals("融资租赁")) {

            for (int i = 0; i < repaymentaRZEntityList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentaRZEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(2);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentDao.add(repaymentEntity);
                }

            }
        }
        //判断购买方式是否为融资租赁打包->插入分期表
        if (contractMainEntity.getBuyType().equals("融资租赁打包")) {
            for (int i = 0; i < repaymentaRZDBEntityList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentaRZDBEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(4);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentDao.add(repaymentEntity);
                }
            }
        }

        //判断是否为置换
        if (contractMainEntity.getHaveReplacement() == 1) {
            //判断新增还是修改
            List<ReplacementEntity> replacementEntityList = (List<ReplacementEntity>) (Object) replacementDao.getIBaseEntityByCondition(" and main_id=?", new String[]{mainId});
            if (null != replacementEntityList && replacementEntityList.size() > 0) { //修改
                String replacementsName = replacementEntity.getReplacementsName();
                //["zzj","wjj"]--->去掉JSON数组格式的符号
                replacementsName = replacementsName.replace("[", "");
                replacementsName = replacementsName.replace("]", "");
                replacementsName = replacementsName.replace("\"", "");
                replacementEntity.setReplacementsName(replacementsName);
                replacementDao.update(replacementEntity);

                String replacementId = replacementEntity.getId();
                if (!StringUtils.isBlank(replacementsName)) {
                    //如果replacementsName中没有旧挖掘机，而旧机表中有，说明合同中删除了原来的挖掘机，则同步删除旧机表中对应的挖掘机（其他旧设备同理）
                    List<JSONObject> disList = deviceDisplaceDao.getJSONListByCondition("and REPLACEMENT_ID=? ", new Object[]{replacementId});
                    String disType = "";
                    for (JSONObject json : disList) {
                        disType = disType + String.valueOf(json.getString("type")) + ",";
                    }
                    disType = disType.substring(0, disType.length() - 1);

                    if (replacementsName.indexOf("wjj") == -1 && disType.indexOf("1") != -1) {
                        deviceDisplaceDao.delByCondition("AND REPLACEMENT_ID = ?  AND TYPE=1", new String[]{replacementId});
                    }
                    if (replacementsName.indexOf("qiChe") == -1 && disType.indexOf("2") != -1) {
                        deviceDisplaceDao.delByCondition("AND REPLACEMENT_ID = ?  AND TYPE=2", new String[]{replacementId});
                    }
                    if (replacementsName.indexOf("fangWu") == -1 && disType.indexOf("3") != -1) {
                        deviceDisplaceDao.delByCondition("AND REPLACEMENT_ID = ?  AND TYPE=3", new String[]{replacementId});
                    }
                    if (replacementsName.indexOf("zzj") == -1 && disType.indexOf("4") != -1) {
                        deviceDisplaceDao.delByCondition("AND REPLACEMENT_ID = ?  AND TYPE=4", new String[]{replacementId});
                    }
                    if (replacementsName.indexOf("other") == -1 && disType.indexOf("5") != -1) {
                        deviceDisplaceDao.delByCondition("AND REPLACEMENT_ID = ?  AND TYPE=5", new String[]{replacementId});
                    }
                    String[] replacementsNames = replacementsName.split(",");
                    for (String rName : replacementsNames) {
                        switch (rName) {
                            //1-旧挖掘机，2-旧汽车，3-旧房屋，4-旧装载机，5-合同的其他情况
                            case "zzj":
                                List<DeviceDisplaceEntity> zzjList = replacementEntity.getZzj();
                                if (null != zzjList) {
                                    for (DeviceDisplaceEntity zzj : zzjList) {
                                        zzj.setReplacementId(replacementId);
                                        zzj.setType(4);
                                        zzj.setDelFlag(0);
                                        zzj.setReplacementType("装载机");
                                        if (!StringUtils.isBlank(zzj.getId())) {//修改已有旧设备
                                            Date createTime = deviceDisplaceDao.getJSONById(zzj.getId()).getDate("createTime");
                                            zzj.setCreateTime(createTime);
                                            deviceDisplaceDao.update(zzj);
                                        } else { //新增旧设备
                                            this.addOldReplacement(replacementEntity, mainId, contractMainEntity,"zzj",zzj);
                                        }

                                    }
                                }
                                break;
                            case "wjj":
                                List<DeviceDisplaceEntity> wjjList = replacementEntity.getWjj();
                                if (null != wjjList) {
                                    for (DeviceDisplaceEntity wjj : wjjList) {
                                        wjj.setReplacementId(replacementId);
                                        wjj.setType(1);
                                        wjj.setDelFlag(0);
                                        wjj.setReplacementType("挖掘机");
                                        if (!StringUtils.isBlank(wjj.getId())) {//修改已有旧设备
                                            Date createTime = deviceDisplaceDao.getJSONById(wjj.getId()).getDate("createTime");
                                            wjj.setCreateTime(createTime);
                                            deviceDisplaceDao.update(wjj);
                                        } else { //新增旧设备
                                            this.addOldReplacement(replacementEntity, mainId, contractMainEntity,"wjj",wjj);
                                        }

                                    }
                                }
                                break;
                            case "qiChe":
                                List<DeviceDisplaceEntity> qiCheList = replacementEntity.getQiChe();
                                if (null != qiCheList) {
                                    for (DeviceDisplaceEntity qiChe : qiCheList) {
                                        qiChe.setReplacementId(replacementId);
                                        qiChe.setType(2);
                                        qiChe.setDelFlag(0);
                                        qiChe.setReplacementType("汽车");
                                        if (!StringUtils.isBlank(qiChe.getId())) {//修改已有旧设备
                                            Date createTime = deviceDisplaceDao.getJSONById(qiChe.getId()).getDate("createTime");
                                            qiChe.setCreateTime(createTime);
                                            deviceDisplaceDao.update(qiChe);
                                        } else { //新增旧设备
                                            this.addOldReplacement(replacementEntity, mainId, contractMainEntity,"qiChe",qiChe);
                                        }

                                    }
                                }
                                break;
                            case "fangWu":
                                List<DeviceDisplaceEntity> fangWuList = replacementEntity.getFangWu();
                                if (null != fangWuList) {
                                    for (DeviceDisplaceEntity fangWu : fangWuList) {
                                        fangWu.setReplacementId(replacementId);
                                        fangWu.setType(3);
                                        fangWu.setDelFlag(0);
                                        fangWu.setReplacementType("房屋");
                                        if (!StringUtils.isBlank(fangWu.getId())) {//修改已有旧设备
                                            Date createTime = deviceDisplaceDao.getJSONById(fangWu.getId()).getDate("createTime");
                                            fangWu.setCreateTime(createTime);
                                            deviceDisplaceDao.update(fangWu);
                                        } else { //新增旧设备
                                            this.addOldReplacement(replacementEntity, mainId, contractMainEntity,"fangWu",fangWu);
                                        }

                                    }
                                }
                                break;
                            case "other":
                                List<DeviceDisplaceEntity> otherList = replacementEntity.getOther();
                                if (null != otherList) {
                                    for (DeviceDisplaceEntity other : otherList) {
                                        other.setReplacementId(replacementId);
                                        other.setType(5);
                                        other.setDelFlag(0);
                                        other.setReplacementType("其他");
                                        if (!StringUtils.isBlank(other.getId())) {//修改已有旧设备
                                            Date createTime = deviceDisplaceDao.getJSONById(other.getId()).getDate("createTime");
                                            other.setCreateTime(createTime);
                                            deviceDisplaceDao.update(other);
                                        } else { //新增旧设备
                                            this.addOldReplacement(replacementEntity, mainId, contractMainEntity,"other",other);
                                        }

                                    }
                                }
                                break;
                        }
                    }
                }

            } else { //新增
                replacementEntity.setMainId(mainId);
                String replacementsName = replacementEntity.getReplacementsName();
                //["zzj","wjj"]--->去掉JSON数组格式的符号
                replacementsName = replacementsName.replace("[", "");
                replacementsName = replacementsName.replace("]", "");
                replacementsName = replacementsName.replace("\"", "");
                replacementEntity.setReplacementsName(replacementsName);
                //添加置换主表的信息
                replacementDao.add(replacementEntity);
                String replacementId = replacementEntity.getId();
                //创建人（id，name），审核状态，审核人，库存状态（提车在途），修改人（id，name）
                String createUserId = contractMainEntity.getCreateUserId();
                String createUserName = contractMainEntity.getCreateUserName();
                String updateUserId = contractMainEntity.getCreateUserId();
                String updateUserName = contractMainEntity.getCreateUserName();
                String regionId = contractMainEntity.getRegionId();
                String regionName = contractMainEntity.getRegionName();
                String bigRegionManagerId = contractMainEntity.getBigRegionManagerId();
                String bigRegionManagerName = contractMainEntity.getBigRegionManagerName();
                String regionManegerId = contractMainEntity.getRegionManagerId();
                String regionManegerName = contractMainEntity.getRegionManagerName();

                String customerName = contractMainEntity.getBuyer();
                String replacementDeviceModelName = contractMainEntity.getModelName();
                String replacementDeviceBrandName = contractMainEntity.getBrandName();
                String replacementDeviceSequence = contractMainEntity.getSerialNo();

                String auditFlag = "-1";//新增旧机置换状态默认为草稿
                //新增旧机置换，审核人默认为曹国玉
                String currentAuditorId = "201711271733404C9DA1461F2421F828";
                String currentAuditorName = "曹国玉";
                String currentAuditorRoleName = userDao.getViewByUserId(" and id=?", new Object[]{currentAuditorId}).get(0).getString("roleName");
                String companyId = contractMainEntity.getSellerCompanyId();
                JSONObject json = companyDao.getJSONById(companyId);
                String companyName = json.getString("name");
                String stockState = "提车在途";
                if (!StringUtils.isBlank(replacementsName)) {
                    String[] replacementsNames = replacementsName.split(",");
                    for (String rName : replacementsNames) {
                        switch (rName) {
                            //1-旧挖掘机，2-旧汽车，3-旧房屋，4-旧装载机，5-合同的其他情况
                            case "zzj":
                                List<DeviceDisplaceEntity> zzjList = replacementEntity.getZzj();
                                if (null != zzjList) {
                                    for (DeviceDisplaceEntity zzj : zzjList) {
                                        zzj.setReplacementId(replacementId);
                                        zzj.setType(4);
                                        zzj.setDelFlag(0);
                                        zzj.setReplacementType("装载机");
                                        zzj = this.setAttribute(zzj, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                        deviceDisplaceDao.add(zzj);
                                        this.saveAudit(zzj.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                                    }
                                }
                                break;
                            case "wjj":
                                List<DeviceDisplaceEntity> wjjList = replacementEntity.getWjj();
                                if (null != wjjList) {
                                    for (DeviceDisplaceEntity wjj : wjjList) {
                                        wjj.setReplacementId(replacementId);
                                        wjj.setType(1);
                                        wjj.setDelFlag(0);
                                        wjj.setReplacementType("挖掘机");
                                        wjj = this.setAttribute(wjj, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                        deviceDisplaceDao.add(wjj);
                                        this.saveAudit(wjj.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                                    }
                                }
                                break;
                            case "qiChe":
                                List<DeviceDisplaceEntity> qiCheList = replacementEntity.getQiChe();
                                if (null != qiCheList) {
                                    for (DeviceDisplaceEntity qiChe : qiCheList) {
                                        qiChe.setReplacementId(replacementId);
                                        qiChe.setType(2);
                                        qiChe.setDelFlag(0);
                                        qiChe.setReplacementType("汽车");
                                        qiChe = this.setAttribute(qiChe, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                        deviceDisplaceDao.add(qiChe);
                                        this.saveAudit(qiChe.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                                    }
                                }
                                break;
                            case "fangWu":
                                List<DeviceDisplaceEntity> fangWuList = replacementEntity.getFangWu();
                                if (null != fangWuList) {
                                    for (DeviceDisplaceEntity fangWu : fangWuList) {
                                        fangWu.setReplacementId(replacementId);
                                        fangWu.setType(3);
                                        fangWu.setDelFlag(0);
                                        fangWu.setReplacementType("房屋");
                                        fangWu = this.setAttribute(fangWu, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                        deviceDisplaceDao.add(fangWu);
                                        this.saveAudit(fangWu.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                                    }
                                }
                                break;
                            case "other":
                                List<DeviceDisplaceEntity> otherList = replacementEntity.getOther();
                                if (null != otherList) {
                                    for (DeviceDisplaceEntity other : otherList) {
                                        other.setReplacementId(replacementId);
                                        other.setType(5);
                                        other.setDelFlag(0);
                                        other.setReplacementType("其他");
                                        other = this.setAttribute(other, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                        deviceDisplaceDao.add(other);
                                        this.saveAudit(other.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                                    }
                                }
                                break;
                        }
                    }
                }
            }
        }
        //添加合同条款信息
        if (null != contractTermsEntityList && contractTermsEntityList.size() > 0) {


            for (int i = 0; i < contractTermsEntityList.size(); i++) {
                ContractTermsEntity contractTermsEntity = contractTermsEntityList.get(i);
                int termLength = contractTermsEntity.getContractTerms().length();
                int termIndex = contractTermsEntity.getContractTerms().indexOf("、");
                if (termLength - termIndex > 1) {
                    contractTermsEntity.setMainId(mainId);
                    contractTermsEntity.setSortNo(i);
                    String contractTerm = contractTermsEntity.getContractTerms();
                    String termsNo = contractTerm.substring(0, termIndex + 1);
                    String contractTerms = contractTerm.substring(termIndex + 1, termLength);
                    contractTermsEntity.setContractTerms(contractTerms);
                    contractTermsEntity.setTermsNo(termsNo);
                    contractTermsDao.add(contractTermsEntity);
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    public void addOldReplacement(ReplacementEntity replacementEntity, String mainId, ContractMainEntity contractMainEntity,String rName,DeviceDisplaceEntity deviceDisplaceEntity) { //新增旧设备置换
        String replacementsName = replacementEntity.getReplacementsName();
        String replacementId = replacementEntity.getId();
        //创建人（id，name），审核状态，审核人，库存状态（提车在途），修改人（id，name）
        String createUserId = contractMainEntity.getCreateUserId();
        String createUserName = contractMainEntity.getCreateUserName();
        String updateUserId = contractMainEntity.getCreateUserId();
        String updateUserName = contractMainEntity.getCreateUserName();
        String regionId = contractMainEntity.getRegionId();
        String regionName = contractMainEntity.getRegionName();
        String bigRegionManagerId = contractMainEntity.getBigRegionManagerId();
        String bigRegionManagerName = contractMainEntity.getBigRegionManagerName();
        String regionManegerId = contractMainEntity.getRegionManagerId();
        String regionManegerName = contractMainEntity.getRegionManagerName();

        String customerName = contractMainEntity.getBuyer();
        String replacementDeviceModelName = contractMainEntity.getModelName();
        String replacementDeviceBrandName = contractMainEntity.getBrandName();
        String replacementDeviceSequence = contractMainEntity.getSerialNo();

        String auditFlag = "-1";//新增旧机置换状态默认为草稿
        //新增旧机置换，审核人默认为曹国玉
        String currentAuditorId = "201711271733404C9DA1461F2421F828";
        String currentAuditorName = "曹国玉";
        String currentAuditorRoleName = userDao.getViewByUserId(" and id=?", new Object[]{currentAuditorId}).get(0).getString("roleName");
        String companyId = contractMainEntity.getSellerCompanyId();
        JSONObject json = companyDao.getJSONById(companyId);
        String companyName = json.getString("name");
        String stockState = "提车在途";
                switch (rName) {
                    //1-旧挖掘机，2-旧汽车，3-旧房屋，4-旧装载机，5-合同的其他情况
                    case "zzj":
                        deviceDisplaceEntity.setReplacementId(replacementId);
                        deviceDisplaceEntity.setType(4);
                        deviceDisplaceEntity.setDelFlag(0);
                        deviceDisplaceEntity.setReplacementType("装载机");
                        deviceDisplaceEntity = this.setAttribute(deviceDisplaceEntity, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                deviceDisplaceDao.add(deviceDisplaceEntity);
                                this.saveAudit(deviceDisplaceEntity.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                        break;
                    case "wjj":
                        deviceDisplaceEntity.setReplacementId(replacementId);
                        deviceDisplaceEntity.setType(1);
                        deviceDisplaceEntity.setDelFlag(0);
                        deviceDisplaceEntity.setReplacementType("挖掘机");
                        deviceDisplaceEntity = this.setAttribute(deviceDisplaceEntity, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                deviceDisplaceDao.add(deviceDisplaceEntity);
                                this.saveAudit(deviceDisplaceEntity.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                        break;
                    case "qiChe":
                        deviceDisplaceEntity.setReplacementId(replacementId);
                        deviceDisplaceEntity.setType(2);
                        deviceDisplaceEntity.setDelFlag(0);
                        deviceDisplaceEntity.setReplacementType("汽车");
                        deviceDisplaceEntity = this.setAttribute(deviceDisplaceEntity, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                deviceDisplaceDao.add(deviceDisplaceEntity);
                                this.saveAudit(deviceDisplaceEntity.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                        break;
                    case "fangWu":
                        deviceDisplaceEntity.setReplacementId(replacementId);
                        deviceDisplaceEntity.setType(3);
                        deviceDisplaceEntity.setDelFlag(0);
                        deviceDisplaceEntity.setReplacementType("房屋");
                        deviceDisplaceEntity = this.setAttribute(deviceDisplaceEntity, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                deviceDisplaceDao.add(deviceDisplaceEntity);
                                this.saveAudit(deviceDisplaceEntity.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                        break;
                    case "other":
                        deviceDisplaceEntity.setReplacementId(replacementId);
                        deviceDisplaceEntity.setType(5);
                        deviceDisplaceEntity.setDelFlag(0);
                        deviceDisplaceEntity.setReplacementType("其他");
                        deviceDisplaceEntity = this.setAttribute(deviceDisplaceEntity, createUserId, createUserName, updateUserId, updateUserName, auditFlag, currentAuditorId, currentAuditorName, currentAuditorRoleName, stockState, companyId, companyName, customerName, replacementDeviceModelName, replacementDeviceBrandName, replacementDeviceSequence, regionManegerId, regionManegerName, bigRegionManagerId, bigRegionManagerName, regionName, regionId);
                                deviceDisplaceDao.add(deviceDisplaceEntity);
                                this.saveAudit(deviceDisplaceEntity.getId(), currentAuditorId, currentAuditorName, currentAuditorRoleName, Integer.parseInt(auditFlag));
                        break;
                }
    }

    public DeviceDisplaceEntity setAttribute(DeviceDisplaceEntity deviceDisplaceEntity, String createUserId, String createUserName, String updateUserId, String updateUserName,
                                             String auditFlag, String currentAuditorId, String currentAuditorName, String currentAuditorRoleName, String stockState, String companyId, String companyName, String customerName, String replacementDeviceModelName, String replacementDeviceBrandName, String replacementDeviceSequence, String regionManegerId, String regionManegerName, String bigRegionManagerId, String bigRegionManagerName, String regionName, String regionId) {
        deviceDisplaceEntity.setCreateUserId(createUserId);
        deviceDisplaceEntity.setCreateUserName(createUserName);
        deviceDisplaceEntity.setUpdateUserId(updateUserId);
        deviceDisplaceEntity.setUpdateUserName(updateUserName);
        deviceDisplaceEntity.setAuditFlag(Integer.parseInt(auditFlag));
        deviceDisplaceEntity.setAuditId(currentAuditorId);
        deviceDisplaceEntity.setAuditName(currentAuditorName);
        deviceDisplaceEntity.setAuditRoleName(currentAuditorRoleName);
        deviceDisplaceEntity.setState(stockState);
        deviceDisplaceEntity.setFkCompanyId(companyId);
        deviceDisplaceEntity.setCompanyName(companyName);
        deviceDisplaceEntity.setCustomerName(customerName);
        deviceDisplaceEntity.setReplacementDeviceBrandName(replacementDeviceBrandName);
        deviceDisplaceEntity.setReplacementDeviceModelName(replacementDeviceModelName);
        deviceDisplaceEntity.setReplacementDeviceSequence(replacementDeviceSequence);
        deviceDisplaceEntity.setRegionId(regionId);
        deviceDisplaceEntity.setRegionName(regionName);
        deviceDisplaceEntity.setRegionManagerId(regionManegerId);
        deviceDisplaceEntity.setRegionManagerName(regionManegerName);
        deviceDisplaceEntity.setBigregionManagerId(bigRegionManagerId);
        deviceDisplaceEntity.setBigregionManagerName(bigRegionManagerName);
        deviceDisplaceEntity.setWhetherToClose("0");
        return deviceDisplaceEntity;
    }

    //新增审核记录
    public Integer saveAudit(String mainId, String parentId, String parentName, String parentRoleName, Integer auditFlag) {
        AuditEntity auditEntity = new AuditEntity();
        Integer auditSort = 0;
        String modelName = "oldSample";
        auditEntity.setMainId(mainId);//旧设备表ID
        auditEntity.setAuditorId(parentId);//审核人Id
        auditEntity.setAuditorName(parentName);//审核人姓名
        auditEntity.setRoleName(parentRoleName);//审核人职位
        auditEntity.setAuditFlag(auditFlag);//审核状态
        auditEntity.setAuditSort(auditSort);
        auditEntity.setModuleName(modelName);
        return auditDao.add(auditEntity);
    }

    //应收台账保存方法
    @Override
    public JSONObject receivableSave(String jsonData) {
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//主表信息
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资分期
        List<FinancingEntity> financingRZEntityList = model.getFinancingRZList();//融资分期款跟踪
        List<FinancingEntity> financingRZDBEntityList = model.getFinancingRZDBList();//融资分期款跟踪
        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资分期
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        List<CollectionEntity> collectionList = model.getCollectionList();//催款记录
        List<ContractHistoryEntity> regionManagerList = model.getRegionManagerList();//区域经理
        List<ContractHistoryEntity> bigRegionManagerList = model.getBigRegionManagerList();//大区经理
        List<ContractHistoryEntity> regionSupportList = model.getRegionSupportList();//区域支持
        List<ContractHistoryEntity> creditorManagerList = model.getCreditorManagerList();//债权经理
        List<ContractHistoryEntity> dataManagerList = model.getDataManagerList();//应收专员
        //主表信息
        ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());
        contractMainEntity.setCreateTime(mainEntity.getCreateTime());
        if (contractMainEntity.getCustomerCredit().equals("已结清")) {
            contractMainEntity.setHaveSettle(1);
        }
        String mainId = contractMainEntity.getId();//主表的ID
        //删除历史人员记录
        contractHistoryDao.removeByCondition(" AND MAIN_ID=?", new String[]{mainId});
        //添加人员
        if (null != regionManagerList && regionManagerList.size() > 0) {
            for (int i = 0; i < regionManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(regionManagerList.get(i).getHistoryManagerId());
                regionManagerList.get(i).setMainId(mainId);
                regionManagerList.get(i).setType(0);
                regionManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        regionManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        regionManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(regionManagerList.get(i));
            }
            contractMainEntity.setTakeOverManagerId(
                    regionManagerList.get(regionManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setTakeOverManager(
                    regionManagerList.get(regionManagerList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != bigRegionManagerList && bigRegionManagerList.size() > 0) {
            for (int i = 0; i < bigRegionManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(bigRegionManagerList.get(i).getHistoryManagerId());
                bigRegionManagerList.get(i).setMainId(mainId);
                bigRegionManagerList.get(i).setType(1);
                bigRegionManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        bigRegionManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        bigRegionManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(bigRegionManagerList.get(i));
            }
            contractMainEntity.setBigRegionManagerId(
                    bigRegionManagerList.get(bigRegionManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setBigRegionManagerName(
                    bigRegionManagerList.get(bigRegionManagerList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != regionSupportList && regionSupportList.size() > 0) {
            for (int i = 0; i < regionSupportList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(regionSupportList.get(i).getHistoryManagerId());
                regionSupportList.get(i).setMainId(mainId);
                regionSupportList.get(i).setType(2);
                regionSupportList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        regionSupportList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        regionSupportList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(regionSupportList.get(i));
            }
            contractMainEntity.setRegionalSupportId(
                    regionSupportList.get(regionSupportList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setRegionalSupportName(
                    regionSupportList.get(regionSupportList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != creditorManagerList && creditorManagerList.size() > 0) {
            for (int i = 0; i < creditorManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(creditorManagerList.get(i).getHistoryManagerId());
                creditorManagerList.get(i).setMainId(mainId);
                creditorManagerList.get(i).setType(3);
                creditorManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        creditorManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        creditorManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(creditorManagerList.get(i));
            }
            contractMainEntity.setCreditManagerId(
                    creditorManagerList.get(creditorManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setCreditManagerName(
                    creditorManagerList.get(creditorManagerList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != dataManagerList && dataManagerList.size() > 0) {
            for (int i = 0; i < dataManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(dataManagerList.get(i).getHistoryManagerId());
                dataManagerList.get(i).setMainId(mainId);
                dataManagerList.get(i).setType(4);
                dataManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        dataManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        dataManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(dataManagerList.get(i));
            }
            contractMainEntity.setDataOfficerId(
                    dataManagerList.get(dataManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setDataOfficerName(
                    dataManagerList.get(dataManagerList.size() - 1).getHistoryManagerName()
            );
        }
        //修改主表信息
        contractMainDao.update(contractMainEntity);
        //首付款信息
        if (null != repaymentaSFEntityList && repaymentaSFEntityList.size() > 0) {
            getRepaymentSave(repaymentaSFEntityList, mainId);
        }
        //首付款垫款信息
        if (contractMainEntity.getHaveRepayment() == 1) {
            if (null != repaymentaDKEntityList && repaymentaDKEntityList.size() > 0) {
                getRepaymentSave(repaymentaDKEntityList, mainId);
            }
        }
        //催收记录
        if (null != collectionList && collectionList.size() > 0) {
            for (int i = 0; i < collectionList.size(); i++) {
                CollectionEntity entity = collectionList.get(i);
                if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
                    if (StringUtils.isNotEmpty(entity.getCollection())) {
                        entity.setMainId(mainId);
                        entity.setSortNo(i);
                        collectionDao.add(entity);
                    }
                } else {
                    CollectionEntity collectionEntity = (CollectionEntity) collectionDao.getIBaseEntityById(entity.getId());
                    if (StringUtils.isNotEmpty(entity.getCollection())) {
                        entity.setCreateTime(collectionEntity.getCreateTime());
                        collectionDao.update(entity);
                    }
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("flag", true);
        return result;
    }

    //公共保存方法
    private void getRepaymentSave(List<RepaymentEntity> repaymentaSFEntityList, String mainId) {
        for (int i = 0; i < repaymentaSFEntityList.size(); i++) {
            RepaymentEntity repaymentEntity = repaymentaSFEntityList.get(i);
            if ("0".equals(repaymentEntity.getId()) || StringUtils.isBlank(repaymentEntity.getId())) {
                //模块0-内部分期/1-垫款/2-融资分期/3-首付款信息
                repaymentEntity.setType(3);
                repaymentEntity.setMainId(mainId);
                repaymentEntity.setSortNo(i);
                repaymentDao.add(repaymentEntity);
            } else {
                RepaymentEntity entity = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentEntity.getId());
                entity.setMainId(mainId);
                entity.setTotal(repaymentEntity.getTotal());
                entity.setRepaymentDate(repaymentEntity.getRepaymentDate());
                entity.setActualRepaymentDate(repaymentEntity.getActualRepaymentDate());
                entity.setRepaymentAmount(repaymentEntity.getRepaymentAmount());
                entity.setOverduePenalty(repaymentEntity.getOverduePenalty());
                entity.setRemainingArrears(repaymentEntity.getRemainingArrears());
                entity.setRemark(repaymentEntity.getRemark());
                entity.setRepaymentAttachName(repaymentEntity.getRepaymentAttachName());
                entity.setRepaymentAttachUrl(repaymentEntity.getRepaymentAttachUrl());
                entity.setCreateUserName(repaymentEntity.getCreateUserName());
                entity.setCreateUserId(repaymentEntity.getCreateUserId());
                repaymentDao.update(entity);
            }
            //保存&修改子list
            if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                    RepaymentEntity entityParent = (RepaymentEntity) repaymentDao.getIBaseEntityById(
                            repaymentEntity.getRepaymentParentList().get(j).getId());
                    if ("0".equals(entityParent.getId()) || StringUtils.isBlank(entityParent.getId())) {
                        repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                        repaymentEntity.getRepaymentParentList().get(j).setType(3);
                        repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                        repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                        repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                    } else {
                        entityParent.setMainId(mainId);
                        entityParent.setActualRepaymentDate(repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate());
                        entityParent.setRepaymentAmount(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                        entityParent.setOverduePenalty(repaymentEntity.getRepaymentParentList().get(j).getOverduePenalty());
                        entityParent.setRemainingArrears(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                        entityParent.setRemark(repaymentEntity.getRepaymentParentList().get(j).getRemark());
                        entityParent.setRepaymentAttachName(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAttachName());
                        entityParent.setRepaymentAttachUrl(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAttachUrl());
                        entityParent.setCreateUserName(repaymentEntity.getRepaymentParentList().get(j).getCreateUserName());
                        entityParent.setCreateUserId(repaymentEntity.getRepaymentParentList().get(j).getCreateUserId());
                        repaymentDao.update(entityParent);
                    }
                }
            }
        }
    }

    //判断是否逾期
    private void getOverDue(String mainId, BigDecimal yqSum, String dateTime, BigDecimal total, String repaymentDate, String nowDate) {
        ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (StringUtils.isBlank(dateTime)) {
            dateTime = nowDate;
        }
        if (total.compareTo(yqSum) > 0 &&
                dateTime.compareTo(repaymentDate) >= 0) {
            if (mainEntity.getHaveOverdue() == 0) {
                Integer haveOverdueNo = DateUtils.getDaySub(repaymentDate, dateTime);
                if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                    mainEntity.setHaveOverdue(1);
                    flag = false;
                    mainEntity.setHaveOverdueNo(haveOverdueNo + 1);
                    contractMainDao.update(mainEntity);
                } else {
                    if (repaymentDate.compareTo(nowDate) <= 0) {
                        Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentDate);
                        flag = false;
                        mainEntity.setHaveOverdue(1);
                        mainEntity.setHaveOverdueNo(overdueNo + 1);
                        contractMainDao.update(mainEntity);
                    }
                }
            }
        } else {
            if (mainEntity.getHaveOverdue() != 2) {
                if (flag) {
                    mainEntity.setHaveOverdue(0);
                    mainEntity.setHaveOverdueNo(-6);
                    contractMainDao.update(mainEntity);

                }
            }
        }
    }


    @Override
    public JSONObject newContract(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonPalams.getString("userId");
        String regionManagerId = jsonPalams.getString("regionManagerId");
        //获取合同制作人信息
        JSONObject users = userDao.getViewJSONById(userId);
        //创建总的的实体对象
        ContractEntity entity = new ContractEntity();
        //创建所有的合同表的实体
        ContractMainEntity contractMainEntity = new ContractMainEntity();
        ContractSalesEntity contractSalesEntity = new ContractSalesEntity();
        ReplacementEntity replacementEntity = new ReplacementEntity();
        GuarantorEntity guarantorEntity = new GuarantorEntity();
        RepaymentEntity repaymentDKEntity = new RepaymentEntity();//垫款
        RepaymentEntity repaymentFQEntity = new RepaymentEntity();//内部分期
        RepaymentEntity repaymentRZEntity = new RepaymentEntity();//融资(应收台账)
        RepaymentEntity repaymentRZDBEntity = new RepaymentEntity();//融资打包(应收台账)
        RepaymentEntity repaymentSFEntity = new RepaymentEntity();//首付款信息
        FinancingEntity financingRZList = new FinancingEntity();//融资分期跟踪
        FinancingEntity financingRZDBList = new FinancingEntity();//融资打包分期跟踪

        RepaymentEntity repaymentFQFirstEntity = new RepaymentEntity();//分期首付款分期
        DeviceDisplaceEntity deviceDisplaceEntity = new DeviceDisplaceEntity();//置换
        //赋值
        //模块->0-内部分期/1-垫款/2-融资分期/3-首付款
        repaymentDKEntity.setType(1);
        repaymentFQEntity.setType(0);
        repaymentRZEntity.setType(2);
        repaymentSFEntity.setType(3);
        repaymentRZDBEntity.setType(4);
        contractMainEntity.setAuditFlag("-1");
        contractMainEntity.setCreateUserName(users.getString("name"));
        List<GuarantorEntity> guarantorList = new ArrayList<GuarantorEntity>();
        guarantorList.add(guarantorEntity);
        List<RepaymentEntity> repaymentDKEntityList = new ArrayList<RepaymentEntity>();
        repaymentDKEntityList.add(repaymentDKEntity);
        List<RepaymentEntity> repaymentFQEntityList = new ArrayList<RepaymentEntity>();
        repaymentFQEntityList.add(repaymentFQEntity);
        List<RepaymentEntity> repaymentRZEntityList = new ArrayList<RepaymentEntity>();
        repaymentRZEntityList.add(repaymentRZEntity);
        List<RepaymentEntity> repaymentSFEntityList = new ArrayList<RepaymentEntity>();
        repaymentSFEntityList.add(repaymentSFEntity);
        List<RepaymentEntity> repaymentRZDBEntityList = new ArrayList<RepaymentEntity>();
        repaymentRZDBEntityList.add(repaymentRZDBEntity);
        List<RepaymentEntity> repaymentFQFirstEntityList = new ArrayList<RepaymentEntity>();
        repaymentFQFirstEntityList.add(repaymentFQFirstEntity);

        List<FinancingEntity> financingRZEntityList = new ArrayList<FinancingEntity>();
        financingRZEntityList.add(financingRZList);

        List<FinancingEntity> financingRZDBEntityList = new ArrayList<FinancingEntity>();
        financingRZDBEntityList.add(financingRZDBList);


        List<ContractTermsEntity> contractTermsEntityList = new ArrayList<ContractTermsEntity>();
        Integer haveTermsNumber = this.haveTermsNumber;
        for (int i = 0; i < contractTermsNumber; i++) {
            ContractTermsEntity contractTermsEntity = new ContractTermsEntity();//合同条款
            contractTermsEntity.setContractTerms(++haveTermsNumber + "、");
            contractTermsEntityList.add(contractTermsEntity);
        }
        //三种置换类型的实体
        //旧挖掘机
        List<DeviceDisplaceEntity> wjj = new ArrayList<DeviceDisplaceEntity>();
        wjj.add(deviceDisplaceEntity);
        replacementEntity.setWjj(wjj);
        //旧装载机
        List<DeviceDisplaceEntity> zzj = new ArrayList<DeviceDisplaceEntity>();
        zzj.add(deviceDisplaceEntity);
        replacementEntity.setZzj(zzj);
        //旧房屋
        List<DeviceDisplaceEntity> fangwu = new ArrayList<DeviceDisplaceEntity>();
        fangwu.add(deviceDisplaceEntity);
        replacementEntity.setFangWu(fangwu);
        //旧汽车
        List<DeviceDisplaceEntity> qiche = new ArrayList<DeviceDisplaceEntity>();
        qiche.add(deviceDisplaceEntity);
        replacementEntity.setQiChe(qiche);
        //其他置换信息
        List<DeviceDisplaceEntity> other = new ArrayList<DeviceDisplaceEntity>();
        other.add(deviceDisplaceEntity);
        replacementEntity.setQiChe(other);
        //放入总的实体
        entity.setSales(contractSalesEntity);
        entity.setMain(contractMainEntity);
        entity.setReplacement(replacementEntity);
        entity.setGuarantorList(guarantorList);
        entity.setRepaymentDKList(repaymentDKEntityList);
        entity.setRepaymentFQList(repaymentFQEntityList);
        entity.setRepaymentRZList(repaymentRZEntityList);
        entity.setRepaymentSFList(repaymentSFEntityList);
        entity.setRepaymentRZDBList(repaymentRZDBEntityList);
        entity.setContractTermsList(contractTermsEntityList);
        entity.setRepaymentFQFirstList(repaymentFQFirstEntityList);
        entity.setFinancingRZList(financingRZEntityList);
        entity.setFinancingRZDBList(financingRZDBEntityList);
        JSONObject JSONentity = (JSONObject) JSON.toJSON(entity);
        JSONObject auditAndcoiper = getJSONByAuditAndCopier(userId, null, "", regionManagerId);
        JSONentity.put("auditors", FastJsonConvert.convertJSONToArray(auditAndcoiper.getString("auditors"), JSONObject.class));
        JSONentity.put("copiers", FastJsonConvert.convertJSONToArray(auditAndcoiper.getString("copiers"), JSONObject.class));
        return JSONentity;
    }

    @Override
    public JSONObject selectContractById(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("id");
        JSONObject jsonObject = getContractByCondition(mainId);
        jsonObject.put("auditors", auditDao.getIBaseEntityByCondition(" AND MAIN_ID=?  AND MODULE_NAME='contractType'  order By auditSort", new Object[]{mainId}));
        jsonObject.put("copiers", copierDao.getIBaseEntityByCondition(" AND MAIN_ID=?  AND MODULE_NAME='contractType' ", new Object[]{mainId}));
        jsonObject.put("history", auditHistoryDao.getEntityListByCondition(" AND MAIN_ID=? AND AUDIT_TYPE=5 AND AUDIT_FLAG='2'", new Object[]{mainId}));
        return jsonObject;
    }

    @Override
    public JSONObject downDocById(String contractId) {
        JSONObject jsonObject = getContractByCondition(contractId);
        JSONObject result = new JSONObject();
        result.put("contract", jsonObject);
        return result;
    }

    //生成新的合同编号
    private String createContractNo(ContractMainEntity contractMainEntity) {
        //获取卖方公司信息
        CompanyEntity companyEntity = companyDao.getById(contractMainEntity.getSellerCompanyId());
        //获取卖方公司ID
        String companyId = companyEntity.getId();
        //获取卖方公司省份
        String companyProvince = companyEntity.getProvince();
        //获取公司名称缩写
        String CompanyNameAbbreviation = contractMainDao.getCompanyFGetpy(companyProvince.substring(0, companyProvince.indexOf("省"))).toUpperCase();
        //获取当前日期
        String Nowdata = DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd");
        //获取当前公司所有合同（AND CREATE_TIME>'2018-10-04 15:40:59'表示这个时间前有些手填合同号不规范，因此去掉这些不规范合同）
        List<ContractMainEntity> contractMainEntityList = (List<ContractMainEntity>) (Object) contractMainDao.getIBaseEntityByCondition(" AND SELLER_COMPANY_ID=? and AUDIT_FLAG =1 and CONTRACT_NO!='-' AND CREATE_TIME>'2018-10-05 14:10:00' order by CONTRACT_NO desc ", new Object[]{companyId});
        //获取当前日期的数字格式
        Nowdata = Nowdata.replace("-", "");
        //1新机 2旧机
        int contractType = contractMainEntity.getContractType();
        String contractNo = null;
        String contractNoLast = "";
        if (contractMainEntityList.size() > 0) {
            ContractMainEntity contractMain = contractMainEntityList.get(0);
            String contractMainContractNo = contractMain.getContractNo();
            //获取合同倒数第二到倒数第五位 HLJ201810020006X 中的 0006
            contractMainContractNo = contractMainContractNo.substring(contractMainContractNo.length() - 5, contractMainContractNo.length() - 1);
            contractNo = Integer.valueOf(Integer.parseInt(contractMainContractNo) + 1).toString();
            switch (contractNo.length()) {
                case 1:
                    contractNo = "000" + contractNo;
                    break;
                case 2:
                    contractNo = "00" + contractNo;
                    break;
                case 3:
                    contractNo = "0" + contractNo;
                    break;
            }
            if (contractType == 1) {
                return CompanyNameAbbreviation + Nowdata + contractNo + "X";
            } else {
                return CompanyNameAbbreviation + Nowdata + contractNo + "J";
            }
        } else {
            //设置初始合同编号
            String lastNo = "";
            switch (companyId) {
                case "2018042608364206B46EC406F62EC079"://黑龙江灜源：0006X
                    lastNo = "0006";
                    break;
                case "20180426083647FCBC7D08C7B14E496E":// 吉林清源：0006X
                    lastNo = "0006";
                    break;
                case "2017121617464DFEB683A82815924552":// 辽宁灜湖：0008X
                    lastNo = "0008";
                    break;
                case "20171216174747FEAED47B7D5A930A0E":// 江苏滚滚向前：0009X
                    lastNo = "0010";
                    break;
                case "2017121617484BB9BEB4A635E7458410":// 安徽灜湖：0014X
                    lastNo = "0014";
                    break;
                case "2017121617474A689E011EEA1635A09D":// 河北灜源：0005X
                    lastNo = "0005";
                    break;
                case "2017121617484B3A8193DB9B6CB372AC":// 甘肃&宁夏：0054X
                    lastNo = "0054";
                    break;
                case "2017121617484353B8D81EEAFB4598A6":// 湖南清源：0026X
                    lastNo = "0026";
                    break;
            }
            if (contractType == 1) {
                return CompanyNameAbbreviation + Nowdata + lastNo + "X";
            } else {
                return CompanyNameAbbreviation + Nowdata + lastNo + "J";
            }
        }
    }

    @Override
    public JSONObject applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        String mainId = jsonPalams.getString("id");//获取主表Id
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String advise = jsonPalams.getString("advise");//意见
        UserEntity userEntity = userDao.getById(userId);//获取当前审核人信息
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);//合同主表信息
        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(mainId);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userEntity.getName());
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
        auditHistoryEntity.setAuditType(5);//合同是5
        auditHistoryDao.add(auditHistoryEntity);
        //更新当前审核人的--审核表记录
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition("and main_id=? and module_name=? and AUDITOR_ID=?", new Object[]{mainId, "contractType", userId});
        if (null != auditEntityList && auditEntityList.size() > 0) {
            AuditEntity auditEntity = auditEntityList.get(0);
            auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
            auditEntity.setAuditAdvise(advise);
            auditEntity.setAuditTime(auditDao.getCurrentTime());
            auditDao.update(auditEntity);
        }
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        List<AuditEntity> auditList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition("and main_id=? and module_name=? order by audit_sort", new Object[]{mainId, "contractType"});
        for (int i = 0; i < auditList.size(); i++) {
            AuditEntity audit = auditList.get(i);
            if (audit.getAuditorId().equals(userId)) {
                //如果是驳回，修改主表状态为驳回->2
                if (auditFlag.equals("2")) {
                    contractMainEntity.setAuditFlag("2");
                    contractMainDao.update(contractMainEntity);
                    //企业号:给合同创建人发送消息
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", contractMainEntity.getCreateUserId());
                    msgObject.put("content", String.format(CONTRACT_APPLICATION_REJECT,
                            contractMainEntity.getCreateUserName(),
                            contractMainEntity.getModelName(),
                            contractMainEntity.getSalesPrice(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    //推送: 给第一审核人推送红点提示
                    //tokenDao.sendJPushMsg(userId, String.format(CONTRACT_AUDIT_AUDIT, userEntity.getName()));
                    //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(mainId, 0);
                    messageReceiverRead(mainId, 2);
                    //付款成功后给申请人发消息，保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(contractMainEntity.getCreateUserId());
                    messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                    messageEntity.setContent(String.format(CONTRACT_APPLICATION_REJECT,
                            contractMainEntity.getCreateUserName(),
                            contractMainEntity.getModelName(),
                            contractMainEntity.getSalesPrice(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(mainId);
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/apply/contract/detail_new.html?id=" + mainId + "&pageType=look&openType=dialog");
                    messageEntity.setOpenTitle(String.format(CONTRACT_APPLICATION_REJECT_MESSAGE, audit.getAuditorName()));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(contractMainEntity.getCreateUserId());
                    messageReceiverEntity.setUserType(2);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                    break;
                }
                //如果是最后一个人审核通过，标记主表状态为通过->1
                if (auditList.size() - 1 == i) {
                    contractMainEntity.setAuditFlag("1");
                    //审核通过，创建合同编号
                    contractMainEntity.setContractNo(createContractNo(contractMainEntity));
                    contractMainDao.update(contractMainEntity);
                    //企业号:给审核人发送消息
                    JSONObject msgObject = new JSONObject();
                    //企业号:给合同申请人发送消息
                    msgObject.put("userIds", contractMainEntity.getCreateUserId());
                    msgObject.put("content", String.format(CONTRACT_APPLICATION_PASS,
                            contractMainEntity.getCreateUserName(),
                            contractMainEntity.getModelName(),
                            contractMainEntity.getSalesPrice(),
                            audit.getAuditorName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    //推送: 给第一审核人推送红点提示
                    //tokenDao.sendJPushMsg(userId, String.format(CONTRACT_AUDIT_NOTIFY, userEntity.getName()));
                    //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(mainId, 0);
                    messageReceiverRead(mainId, 2);
                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(contractMainEntity.getCreateUserId());
                    messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                    messageEntity.setContent(String.format(CONTRACT_APPLICATION_PASS,
                            contractMainEntity.getCreateUserName(),
                            contractMainEntity.getModelName(),
                            contractMainEntity.getSalesPrice(),
                            audit.getAuditorName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(mainId);
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/apply/contract/detail_new.html?id=" + mainId + "&pageType=look&openType=dialog");
                    messageEntity.setOpenTitle(String.format(CONTRACT_APPLICATION_PASS_MESSAGE, audit.getAuditorName()));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(contractMainEntity.getCreateUserId());
                    messageReceiverEntity.setUserType(2);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                }
            } else {
                //下一位审核人才进入，修改审核表状态和主表审核人信息
                if (audit.getAuditFlag().toString().equals("-1")) {
                    audit.setAuditFlag(0);
                    auditDao.update(audit);
                    contractMainEntity.setCurrentAuditorName(audit.getAuditorName());
                    contractMainEntity.setCurrentAuditorId(audit.getAuditorId());
                    contractMainDao.update(contractMainEntity);
                    //企业号:给审核人发送消息
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", audit.getAuditorId());
                    msgObject.put("content", String.format(CONTRACT_AUDIT_AUDIT,
                            audit.getAuditorName(),
                            contractMainEntity.getModelName(),
                            contractMainEntity.getSalesPrice(),
                            contractMainEntity.getCreateUserName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    //推送: 给第一审核人推送红点提示
                    //tokenDao.sendJPushMsg(userId, String.format(CONTRACT_AUDIT_NOTIFY, userEntity.getName()));
                    //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(mainId, 0);
                    messageReceiverRead(mainId, 2);
                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(contractMainEntity.getCreateUserId());
                    messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                    messageEntity.setContent(String.format(CONTRACT_AUDIT_AUDIT,
                            audit.getAuditorName(),
                            contractMainEntity.getModelName(),
                            contractMainEntity.getSalesPrice(),
                            contractMainEntity.getCreateUserName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(mainId);
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/apply/contract/detail_new.html?id=" + mainId + "&pageType=look&openType=dialog");
                    messageEntity.setOpenTitle(String.format(CONTRACT_AUDIT_AUDIT_MESSAGE, contractMainEntity.getCreateUserName()));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(audit.getAuditorId());
                    messageReceiverEntity.setUserType(0);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                    break;
                }
            }

        }
        //曹国玉合同列表页面驳回处理
        if (userId.equals("201711271733404C9DA1461F2421F828") && auditFlag.equals("2") && !contractMainEntity.getAuditFlag().equals("2")) {
            contractMainEntity.setAuditFlag(auditFlag);
            contractMainDao.update(contractMainEntity);
        }
        JSONObject result = new JSONObject();
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    //上传附件
    @Override
    public Boolean uploadFileByContractId(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("contractId");
        //获取合同主表信息
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        //删除现有的附件模块表中的信息
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=10 ", new String[]{mainId});
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=11 ", new String[]{mainId});
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=12 ", new String[]{mainId});
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=13 ", new String[]{mainId});
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=14 ", new String[]{mainId});
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=15 ", new String[]{mainId});
        attachModuleDao.removeByCondition("and MODULE_ID=? and ATTACH_MODULE=16 ", new String[]{mainId});
        //获取上传附件的信息
        int firstNum = 0;
        List<JSONObject> firstList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches1"), JSONObject.class);
        if (!StringUtils.isBlank(mainId) && firstList.size() > 0) {
            for (JSONObject attachModule : firstList) {
                //附件信息写入附件-模板表中
                if (!StringUtils.isBlank(attachModule.getString("id"))) {
                    firstNum++;
                    AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                    AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                    attachModuleEntity.setAttachId(attachmentEntity.getId());
                    attachModuleEntity.setAttachModule(10);//合同是9
                    attachModuleEntity.setModuleId(mainId);
                    attachModuleDao.add(attachModuleEntity);
                }
            }
        }
        //获取上传附件的信息
        int secondNum = 0;
        List<JSONObject> secondList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches2"), JSONObject.class);
        if (!StringUtils.isBlank(mainId) && secondList.size() > 0) {
            for (JSONObject attachModule : secondList) {
                //附件信息写入附件-模板表中
                if (!StringUtils.isBlank(attachModule.getString("id"))) {
                    secondNum++;
                    AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                    AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                    attachModuleEntity.setAttachId(attachmentEntity.getId());
                    attachModuleEntity.setAttachModule(11);//合同是9
                    attachModuleEntity.setModuleId(mainId);
                    attachModuleDao.add(attachModuleEntity);
                }
            }
        }
        //获取上传附件的信息
        int thirdNum = 0;
        List<JSONObject> thirdList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches3"), JSONObject.class);
        if (!StringUtils.isBlank(mainId) && thirdList.size() > 0) {
            for (JSONObject attachModule : thirdList) {
                //附件信息写入附件-模板表中
                if (!StringUtils.isBlank(attachModule.getString("id"))) {
                    thirdNum++;
                    AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                    AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                    attachModuleEntity.setAttachId(attachmentEntity.getId());
                    attachModuleEntity.setAttachModule(12);//合同是9
                    attachModuleEntity.setModuleId(mainId);
                    attachModuleDao.add(attachModuleEntity);
                }
            }
        }
        //获取上传附件的信息
        int fourthNum = 0;
        List<JSONObject> fourthList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches4"), JSONObject.class);
        if (!StringUtils.isBlank(mainId) && fourthList.size() > 0) {
            for (JSONObject attachModule : fourthList) {
                //附件信息写入附件-模板表中
                if (!StringUtils.isBlank(attachModule.getString("id"))) {
                    fourthNum++;
                    AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                    AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                    attachModuleEntity.setAttachId(attachmentEntity.getId());
                    attachModuleEntity.setAttachModule(13);//合同是9
                    attachModuleEntity.setModuleId(mainId);
                    attachModuleDao.add(attachModuleEntity);
                }
            }
        }
        //获取上传附件的信息
        List<JSONObject> fifthList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches5"), JSONObject.class);
        if (!StringUtils.isBlank(mainId) && fifthList.size() > 0) {
            for (JSONObject attachModule : fifthList) {
                //附件信息写入附件-模板表中
                if (!StringUtils.isBlank(attachModule.getString("id"))) {
                    AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                    AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                    attachModuleEntity.setAttachId(attachmentEntity.getId());
                    attachModuleEntity.setAttachModule(14);//合同是9
                    attachModuleEntity.setModuleId(mainId);
                    attachModuleDao.add(attachModuleEntity);
                }
            }
        }
        //获取上传附件的信息
        int sixthNum = 0;
        List<JSONObject> sixthList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches6"), JSONObject.class);
        if (!StringUtils.isBlank(mainId) && sixthList.size() > 0) {
            for (JSONObject attachModule : sixthList) {
                //附件信息写入附件-模板表中
                if (!StringUtils.isBlank(attachModule.getString("id"))) {
                    sixthNum++;
                    AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                    AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                    attachModuleEntity.setAttachId(attachmentEntity.getId());
                    attachModuleEntity.setAttachModule(15);//合同是9
                    attachModuleEntity.setModuleId(mainId);
                    attachModuleDao.add(attachModuleEntity);
                }
            }
        }
        //获取上传附件的信息
        int seventhNum = 0;
        List<JSONObject> seventhList = FastJsonConvert.convertJSONToArray(jsonPalams.getString("attaches7"), JSONObject.class);
        if (!StringUtils.isBlank(mainId) && seventhList.size() > 0) {
            for (JSONObject attachModule : seventhList) {
                //附件信息写入附件-模板表中
                if (!StringUtils.isBlank(attachModule.getString("id"))) {
                    seventhNum++;
                    AttachmentEntity attachmentEntity = JSON.toJavaObject(attachModule, AttachmentEntity.class);
                    AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                    attachModuleEntity.setAttachId(attachmentEntity.getId());
                    attachModuleEntity.setAttachModule(16);//合同是9
                    attachModuleEntity.setModuleId(mainId);
                    attachModuleDao.add(attachModuleEntity);
                }
            }
        }
        /**
         * 判断附件完整程度
         * 都有的：1、签字版销售合同原件扫描件
         *        7、商务条件同意截图
         * 一、个人客户
         **** 融资、内部分期：
         ******* 2、签字版融资合同原件扫描件（融资的需要）
         ******* 3、客户身份证正反面复印件
         ******* 4、户口本首页及本人页复印件
         **** 全款：
         ******* 2、客户身份证正反面复印件
         * 二、公司客户
         **** 融资、内部分期
         ******* 2、签字版融资合同原件扫描件（融资的需要）
         ******* 3、三证合一的营业执照复印件
         ******* 4、法人身份证正反面复印件
         ******* 5、户口本首页及本人页复印件
         **** 全款
         ******* 2、三证合一的营业执照复印件
         *
         */
        //更改合同主表的合同附件字段
        String buyType = contractMainEntity.getBuyType();
        if (matchesCard(contractMainEntity.getBuyerTaxNo())) {
            if (buyType.equals("全款")) {
                if (secondNum > 0 && firstNum > 0 && seventhNum > 0) {
                    contractMainEntity.setHaveUploadContract(1);
                } else {
                    contractMainEntity.setHaveUploadContract(0);
                }
            } else {
                if (!buyType.equals("内部分期")) {
                    if (secondNum > 0 && firstNum > 0 && thirdNum > 0 && sixthNum > 0 && seventhNum > 0) {
                        contractMainEntity.setHaveUploadContract(1);
                    } else {
                        contractMainEntity.setHaveUploadContract(0);
                    }
                } else {
                    if (secondNum > 0 && firstNum > 0 && thirdNum > 0 && seventhNum > 0) {
                        contractMainEntity.setHaveUploadContract(1);
                    } else {
                        contractMainEntity.setHaveUploadContract(0);
                    }
                }
            }
        } else {
            if (buyType.equals("全款")) {
                if (fourthNum > 0 && firstNum > 0 && seventhNum > 0) {
                    contractMainEntity.setHaveUploadContract(1);
                } else {
                    contractMainEntity.setHaveUploadContract(0);
                }
            } else {
                if (!buyType.equals("内部分期")) {
                    if (secondNum > 0 && firstNum > 0 && thirdNum > 0 && sixthNum > 0 && fourthNum > 0 && seventhNum > 0) {
                        contractMainEntity.setHaveUploadContract(1);
                    } else {
                        contractMainEntity.setHaveUploadContract(0);
                    }
                } else {
                    if (secondNum > 0 && firstNum > 0 && thirdNum > 0 && fourthNum > 0 && seventhNum > 0) {
                        contractMainEntity.setHaveUploadContract(1);
                    } else {
                        contractMainEntity.setHaveUploadContract(0);
                    }
                }

            }
        }
        contractMainDao.update(contractMainEntity);
        return true;
    }

    //查看附件
    @Override
    public JSONObject getUploadFileByContractId(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("contractId");
        //10
        List<JSONObject> firstList = new ArrayList<JSONObject>();
        List<JSONObject> firstModuleList = attachModuleDao.getJSONListByCondition("and MODULE_ID=? and ATTACH_MODULE=10", new Object[]{mainId});
        if (firstModuleList.size() > 0) {
            for (JSONObject attachModule : firstModuleList) {
                firstList.add(attachDao.getJSONById(attachModule.getString("attachId")));
            }
        } else {
            JSONObject attachmentEntity = new JSONObject();
            attachmentEntity.put("name", "");
            attachmentEntity.put("url", "");
            attachmentEntity.put("id", "");
            firstList.add(attachmentEntity);
        }
        //11
        List<JSONObject> secondList = new ArrayList<JSONObject>();
        List<JSONObject> secondModuleList = attachModuleDao.getJSONListByCondition("and MODULE_ID=? and ATTACH_MODULE=11", new Object[]{mainId});
        if (secondModuleList.size() > 0) {
            for (JSONObject attachModule : secondModuleList) {
                secondList.add(attachDao.getJSONById(attachModule.getString("attachId")));
            }
        } else {
            JSONObject attachmentEntity = new JSONObject();
            attachmentEntity.put("name", "");
            attachmentEntity.put("url", "");
            attachmentEntity.put("id", "");
            secondList.add(attachmentEntity);
        }
        //12
        List<JSONObject> thirdList = new ArrayList<JSONObject>();
        List<JSONObject> thirdModuleList = attachModuleDao.getJSONListByCondition("and MODULE_ID=? and ATTACH_MODULE=12", new Object[]{mainId});
        if (thirdModuleList.size() > 0) {
            for (JSONObject attachModule : thirdModuleList) {
                thirdList.add(attachDao.getJSONById(attachModule.getString("attachId")));
            }
        } else {
            JSONObject attachmentEntity = new JSONObject();
            attachmentEntity.put("name", "");
            attachmentEntity.put("url", "");
            attachmentEntity.put("id", "");
            thirdList.add(attachmentEntity);
        }
        //13
        List<JSONObject> fourthList = new ArrayList<JSONObject>();
        List<JSONObject> fourthModuleList = attachModuleDao.getJSONListByCondition("and MODULE_ID=? and ATTACH_MODULE=13", new Object[]{mainId});
        if (fourthModuleList.size() > 0) {
            for (JSONObject attachModule : fourthModuleList) {
                fourthList.add(attachDao.getJSONById(attachModule.getString("attachId")));
            }
        } else {
            JSONObject attachmentEntity = new JSONObject();
            attachmentEntity.put("name", "");
            attachmentEntity.put("url", "");
            attachmentEntity.put("id", "");
            fourthList.add(attachmentEntity);
        }
        //14
        List<JSONObject> fifthList = new ArrayList<JSONObject>();
        List<JSONObject> fifthModuleList = attachModuleDao.getJSONListByCondition("and MODULE_ID=? and ATTACH_MODULE=14", new Object[]{mainId});
        if (fifthModuleList.size() > 0) {
            for (JSONObject attachModule : fifthModuleList) {
                fifthList.add(attachDao.getJSONById(attachModule.getString("attachId")));
            }
        } else {
            JSONObject attachmentEntity = new JSONObject();
            attachmentEntity.put("name", "");
            attachmentEntity.put("url", "");
            attachmentEntity.put("id", "");
            fifthList.add(attachmentEntity);
        }
        //15
        List<JSONObject> sixthList = new ArrayList<JSONObject>();
        List<JSONObject> sixthModuleList = attachModuleDao.getJSONListByCondition("and MODULE_ID=? and ATTACH_MODULE=15", new Object[]{mainId});
        if (sixthModuleList.size() > 0) {
            for (JSONObject attachModule : sixthModuleList) {
                sixthList.add(attachDao.getJSONById(attachModule.getString("attachId")));
            }
        } else {
            JSONObject attachmentEntity = new JSONObject();
            attachmentEntity.put("name", "");
            attachmentEntity.put("url", "");
            attachmentEntity.put("id", "");
            sixthList.add(attachmentEntity);
        }
        //16
        List<JSONObject> seventhList = new ArrayList<JSONObject>();
        List<JSONObject> seventhModuleList = attachModuleDao.getJSONListByCondition("and MODULE_ID=? and ATTACH_MODULE=16", new Object[]{mainId});
        if (seventhModuleList.size() > 0) {
            for (JSONObject attachModule : seventhModuleList) {
                seventhList.add(attachDao.getJSONById(attachModule.getString("attachId")));
            }
        } else {
            JSONObject attachmentEntity = new JSONObject();
            attachmentEntity.put("name", "");
            attachmentEntity.put("url", "");
            attachmentEntity.put("id", "");
            seventhList.add(attachmentEntity);
        }

        JSONObject JSONentity = new JSONObject();
        JSONentity.put("attaches1", firstList);
        JSONentity.put("attaches2", secondList);
        JSONentity.put("attaches3", thirdList);
        JSONentity.put("attaches4", fourthList);
        JSONentity.put("attaches5", fifthList);
        JSONentity.put("attaches6", sixthList);
        JSONentity.put("attaches7", seventhList);
        return JSONentity;
    }

    //获取抄送人和收件人
    public JSONObject getJSONByAuditAndCopier(String userId, String mainId, String auditFlag, String regionManagerId) {
        JSONObject results = new JSONObject();
        String userIds = checkDao.getParentByUserId(userId, false);//能看到合同制作人的上级人员
        List<JSONObject> regionManagerObject = null;
        //获取区域经理信息
        JSONObject user = userDao.getViewJSONById(regionManagerId);
        if (!user.getString("jobState").equals("1")) {
            String regionManagerIds = checkDao.getParentByUserId(regionManagerId, false);//能看到区域经理的上级人员
            regionManagerObject = userDao.getUserByUserIdAndRoleName(regionManagerIds, "大区经理", regionManagerId);
        }
        //获取审核人
        List<JSONObject> auditors = new ArrayList<>();
        //第一审核人为集团销售管理
        List<JSONObject> jsonObject = userDao.getUserByUserIdAndRoleName(userIds, "集团销售管理", userId);
        if (jsonObject.size() > 0) {
            auditors.add(jsonObject.get(0));
        }
        //第二审核人为总经理
        jsonObject = userDao.getUserByUserIdAndRoleName(userIds, "总经理", userId);
        if (jsonObject.size() > 0) {
            auditors.add(jsonObject.get(0));
        }
        //第三审核人为曹国玉
        jsonObject = userDao.getUserByUserIdAndRoleName(userIds, "后台管理", userId);
        if (jsonObject.size() > 0) {
            auditors.add(jsonObject.get(0));
        }
        if (mainId != null && auditors.size() > 0) {
            //mainId不为空才添加到数据库，否则只是获取
            for (int i = 0; i < auditors.size(); i++) {
                AuditEntity auditEntity = new AuditEntity();
                auditEntity.setAuditorId(auditors.get(i).getString("userId"));
                auditEntity.setAuditorName(auditors.get(i).getString("auditorName"));
                auditEntity.setRoleName(auditors.get(i).getString("roleName"));
                auditEntity.setAuditSort(i);
                if (i == 0 && !auditFlag.equals("-1")) {
                    //设置第一审核人状态
                    auditEntity.setAuditFlag(0);
                } else {
                    auditEntity.setAuditFlag(-1);
                }
                auditEntity.setModuleName("contractType");//合同类型
                auditEntity.setMainId(mainId);
                auditDao.add(auditEntity);
            }
        }
        results.put("auditors", auditors);
        //查询抄送人
        List<JSONObject> copiers = new ArrayList<>();
        StringBuffer exUserIds = new StringBuffer();
        for (int i = 0; i < auditors.size(); i++) {
            exUserIds.append(" '" + auditors.get(i).getString("userId") + "' ,");
        }
        String condition = "";
        if (!StringUtils.isBlank(exUserIds.toString())) {
            condition = "and v_sys_part_time_for_report.`userId` not in (" + exUserIds.substring(0, exUserIds.length() - 1) + ")";
        }
        copiers = userDao.getUserByUserIdAndRoleName(userIds, "", userId, condition);
        if (null != regionManagerObject && regionManagerObject.size() > 0 && userIds.indexOf(regionManagerObject.get(0).getString("userId")) == -1) {
            JSONObject copier = new JSONObject();
            copier.put("roleName", "大区经理");
            copier.put("userId", regionManagerObject.get(0).getString("userId"));
            copier.put("copierName", regionManagerObject.get(0).getString("auditorName"));
            copiers.add(copier);
        }
        if (mainId != null && copiers.size() > 0) {
            //mainId不为空才添加到数据库，否则只是获取
            for (int i = 0; i < copiers.size(); i++) {
                CopierEntity copierEntity = new CopierEntity();
                copierEntity.setCopierId(copiers.get(i).getString("userId"));
                copierEntity.setCopierName(copiers.get(i).getString("copierName"));
                copierEntity.setModuleName("contractType");//合同类型
                copierEntity.setMainId(mainId);
                copierDao.add(copierEntity);
            }
        }
        results.put("copiers", copiers);
        return results;
    }

    //私有的查询和导出公共的方法
    private JSONObject getContractByCondition(String mainId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ContractEntity entity = new ContractEntity();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (StringUtils.isBlank(contractMainEntity.getCustomerCredit())) {
            if (contractMainEntity.getHaveOverdue() == 1) {
                Integer overdueNo = contractMainEntity.getHaveOverdueNo();
                if (overdueNo <= 30) {
                    contractMainEntity.setCustomerCredit("1-1类：逾期1-30天");
                } else if (31 < overdueNo && overdueNo <= 60) {
                    contractMainEntity.setCustomerCredit("1-2类：逾期31-60天");
                } else {
                    contractMainEntity.setCustomerCredit("1-3类：逾期60天以上");
                }
            } else {
                contractMainEntity.setCustomerCredit("0类：无逾期");
            }
        }
        //查看购买方式是否为内部分期
        if (contractMainEntity.getBuyType().equals("内部分期")) {
            List<RepaymentEntity> repaymentFQList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=0  order by SORT_NO", new Object[]{mainId});//分期列表
            if (repaymentFQList != null && repaymentFQList.size() > 0) {
                for (int i = 0; i < repaymentFQList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentFQList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                }
            }
            entity.setRepaymentFQList(repaymentFQList);
        } else {
            RepaymentEntity repaymentFQEntity = new RepaymentEntity();//内部分期
            List<RepaymentEntity> repaymentaFQEntityList = new ArrayList<RepaymentEntity>();
            repaymentaFQEntityList.add(repaymentFQEntity);
            entity.setRepaymentFQList(repaymentaFQEntityList);
        }
        //查看购买方式是否为内部分期并且有首付款分期
        if (contractMainEntity.getBuyType().equals("内部分期") && contractMainEntity.getHaveFQFirst() == 1) {
            List<RepaymentEntity> repaymentFQFirstList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=5  order by SORT_NO", new Object[]{mainId});//分期首付款分期
            if (repaymentFQFirstList != null && repaymentFQFirstList.size() > 0) {
                for (int i = 0; i < repaymentFQFirstList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentFQFirstList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=5 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                }
            }
            entity.setRepaymentFQFirstList(repaymentFQFirstList);

        } else {
            RepaymentEntity repaymentFQEntity = new RepaymentEntity();//内部分期
            List<RepaymentEntity> repaymentFQFirstList = new ArrayList<RepaymentEntity>();
            repaymentFQFirstList.add(repaymentFQEntity);
            entity.setRepaymentFQFirstList(repaymentFQFirstList);
        }
        //查看购买方式是否为融资租赁
        if (contractMainEntity.getBuyType().equals("融资租赁")) {
            List<RepaymentEntity> repaymentRZList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=2  order by SORT_NO", new Object[]{mainId});//分期列表
            if (null == repaymentRZList || repaymentRZList.size() == 0) {
                RepaymentEntity repaymentRZEntity = new RepaymentEntity();
                repaymentRZList.add(repaymentRZEntity);
            }
            if (repaymentRZList != null && repaymentRZList.size() > 0) {
                for (int i = 0; i < repaymentRZList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentRZList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                }
            }
            entity.setRepaymentRZList(repaymentRZList);
            //融资分期跟踪
            List<FinancingEntity> financingRZList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND PARENT_ID='0' AND TYPE=2 ORDER BY SORT_NO ", new Object[]{mainId});
            if (null == financingRZList || financingRZList.size() == 0) {
                FinancingEntity financingEntity = new FinancingEntity();
                financingRZList.add(financingEntity);
            }
            for (int i = 0; i < financingRZList.size(); i++) {
                FinancingEntity financingEntity = financingRZList.get(i);
                List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getId()});
                financingEntity.setRepaymentParentList(repaymentParentList);
            }
            entity.setFinancingRZList(financingRZList);

        } else {
            RepaymentEntity repaymentRZEntity = new RepaymentEntity();
            List<RepaymentEntity> repaymentaRZEntityList = new ArrayList<RepaymentEntity>();
            repaymentaRZEntityList.add(repaymentRZEntity);
            entity.setRepaymentRZList(repaymentaRZEntityList);
            //融资分期款跟踪
            FinancingEntity financingEntity = new FinancingEntity();
            List<FinancingEntity> financingRZList = new ArrayList<FinancingEntity>();
            financingRZList.add(financingEntity);
            entity.setFinancingRZList(financingRZList);

        }
        //查看购买方式是否为融资租赁打包
        if (contractMainEntity.getBuyType().equals("融资租赁打包")) {
            List<RepaymentEntity> repaymentRZDBList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=4  order by SORT_NO", new Object[]{mainId});//分期列表
            if (null == repaymentRZDBList || repaymentRZDBList.size() == 0) {
                RepaymentEntity repaymentRZDBEntity = new RepaymentEntity();
                repaymentRZDBList.add(repaymentRZDBEntity);
            }
            if (repaymentRZDBList != null && repaymentRZDBList.size() > 0) {
                for (int i = 0; i < repaymentRZDBList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentRZDBList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                }
            }
            entity.setRepaymentRZDBList(repaymentRZDBList);
            //融资分期跟踪
            List<FinancingEntity> financingRZDBList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND PARENT_ID='0' AND TYPE=4  ORDER BY SORT_NO ", new Object[]{mainId});
            if (null == financingRZDBList || financingRZDBList.size() == 0) {
                FinancingEntity financingEntity = new FinancingEntity();
                financingRZDBList.add(financingEntity);
            }
            for (int i = 0; i < financingRZDBList.size(); i++) {
                FinancingEntity financingEntity = financingRZDBList.get(i);
                List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=4  order by SORT_NO", new Object[]{financingEntity.getId()});
                financingEntity.setRepaymentParentList(repaymentParentList);
            }
            entity.setFinancingRZDBList(financingRZDBList);

        } else {
            RepaymentEntity repaymentRZDBEntity = new RepaymentEntity();
            List<RepaymentEntity> repaymentRZDBList = new ArrayList<RepaymentEntity>();
            repaymentRZDBList.add(repaymentRZDBEntity);
            entity.setRepaymentRZDBList(repaymentRZDBList);
        }
        //查看是否有垫款
        if (contractMainEntity.getHaveRepayment() == 1) {
            List<RepaymentEntity> repaymentDKList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0  AND TYPE=1  order by SORT_NO", new Object[]{mainId});//垫款列表
            if (repaymentDKList != null && repaymentDKList.size() > 0) {
                for (int i = 0; i < repaymentDKList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentDKList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                }
            }
            entity.setRepaymentDKList(repaymentDKList);
        }
        //查看是否是置换
        if (contractMainEntity.getHaveReplacement() == 1) {
            List<IBaseEntity> replacement = replacementDao.getIBaseEntityByCondition("AND MAIN_ID=? ", new Object[]{mainId});
            if (null != replacement && replacement.size() > 0) {
                ReplacementEntity replacementEntity = (ReplacementEntity) replacement.get(0);
                List<DeviceDisplaceEntity> zzj = new ArrayList<DeviceDisplaceEntity>();//旧挖掘机
                List<DeviceDisplaceEntity> wjj = new ArrayList<DeviceDisplaceEntity>();//旧装载机
                List<DeviceDisplaceEntity> fangWu = new ArrayList<DeviceDisplaceEntity>();//旧房屋置换
                List<DeviceDisplaceEntity> qiChe = new ArrayList<DeviceDisplaceEntity>();//旧汽车置换
                List<DeviceDisplaceEntity> other = new ArrayList<DeviceDisplaceEntity>();//其他置换信息
                String replacementsName = replacementEntity.getReplacementsName();
                DeviceDisplaceEntity deviceDisplaceEntity = new DeviceDisplaceEntity();
                if (!replacementsName.contains("zzj")) {
                    zzj.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("wjj")) {
                    wjj.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("fangWu")) {
                    fangWu.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("qiChe")) {
                    qiChe.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("other")) {
                    other.add(deviceDisplaceEntity);
                }
                List<DeviceDisplaceEntity> deviceDisplaces = (List<DeviceDisplaceEntity>) (Object) deviceDisplaceDao.getIBaseEntityByCondition("AND REPLACEMENT_ID=? AND DEL_FLAG=0", new Object[]{replacementEntity.getId()});
                for (DeviceDisplaceEntity deviceDisplace : deviceDisplaces) {
                    switch (deviceDisplace.getType()) {
                        //1-旧挖掘机，2-旧汽车，3-旧房屋，4-旧装载机，5-合同的其他情况
                        case 1:
                            wjj.add(deviceDisplace);
                            break;
                        case 2:
                            qiChe.add(deviceDisplace);
                            break;
                        case 3:
                            fangWu.add(deviceDisplace);
                            break;
                        case 4:
                            zzj.add(deviceDisplace);
                            break;
                        case 5:
                            other.add(deviceDisplace);
                            break;
                    }
                }
                //放入实体
                replacementEntity.setWjj(wjj);
                replacementEntity.setZzj(zzj);
                replacementEntity.setFangWu(fangWu);
                replacementEntity.setQiChe(qiChe);
                replacementEntity.setOther(other);
                entity.setReplacement(replacementEntity);
            }
        } else {
            ReplacementEntity replacementEntity = new ReplacementEntity();
            entity.setReplacement(replacementEntity);
        }
        //查询是否有担保人
        List<IBaseEntity> guarantors = guarantorDao.getIBaseEntityByCondition("AND MAIN_ID=? AND LOG_FLAG=0 ", new Object[]{mainId});
        if (null != guarantors && guarantors.size() > 0) {
            List<GuarantorEntity> guarantorList = (List<GuarantorEntity>) (Object) guarantorDao.getIBaseEntityByCondition("AND MAIN_ID=?  AND LOG_FLAG=0  ORDER BY SORT_NO", new Object[]{mainId});//担保人列表
            entity.setGuarantorList(guarantorList);
        } else {
            GuarantorEntity guarantorEntity = new GuarantorEntity();
            guarantorEntity.setLogFlag(0);
            List<GuarantorEntity> guarantorList = new ArrayList<GuarantorEntity>();
            guarantorList.add(guarantorEntity);
            entity.setGuarantorList(guarantorList);
        }
        //查询合同条款
        Integer haveTermsNumber = this.haveTermsNumber;
        List<IBaseEntity> contractTerms = contractTermsDao.getIBaseEntityByCondition("AND MAIN_ID=? AND LOG_FLAG=0", new Object[]{mainId});
        if (null != contractTerms && contractTerms.size() > 0) {
            List<ContractTermsEntity> contractTermsEntityList = (List<ContractTermsEntity>) (Object) contractTermsDao.getIBaseEntityByCondition("AND MAIN_ID=?  AND LOG_FLAG=0 ORDER BY SORT_NO", new Object[]{mainId});//合同条款
            for (ContractTermsEntity contractTermsEntity : contractTermsEntityList) {
                contractTermsEntity.setContractTerms(contractTermsEntity.getTermsNo() + contractTermsEntity.getContractTerms());
            }
            for (int i = 0; i < 3 - contractTerms.size(); i++) {
                ContractTermsEntity contractTermsEntity = new ContractTermsEntity();
                contractTermsEntity.setTermsNo(++haveTermsNumber + contractTerms.size() + "、");
                contractTermsEntityList.add(contractTermsEntity);
            }
            entity.setContractTermsList(contractTermsEntityList);
        } else {
            List<ContractTermsEntity> contractTermsEntityList = new ArrayList<ContractTermsEntity>();
            for (int i = 0; i < contractTermsNumber; i++) {
                ContractTermsEntity contractTermsEntity = new ContractTermsEntity();//合同条款
                contractTermsEntity.setTermsNo(++haveTermsNumber + "、");
                contractTermsEntityList.add(contractTermsEntity);
            }
            entity.setContractTermsList(contractTermsEntityList);
        }
        ContractSalesEntity contractSalesEntity = (ContractSalesEntity) contractSalesDao.getIBaseEntityByCondition("AND MAIN_ID=? AND LOG_FLAG=0 ", new Object[]{mainId}).get(0);
        entity.setSales(contractSalesEntity);
        //添加首付款信息
        List<RepaymentEntity> repaymentSFList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=3 order by SORT_NO", new Object[]{mainId});//首付款信息
        //添加首付款信息分期中的分期
        if (repaymentSFList != null && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentSFList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                repaymentEntity.setRepaymentParentList(repaymentParentList);
            }
        }
        entity.setRepaymentSFList(repaymentSFList);
        //添加合同主表信息
        entity.setMain(contractMainEntity);
        JSONObject jsonObject = (JSONObject) JSON.toJSON(entity);
        return jsonObject;
    }


    //查询冲抵list
    @Override
    public JSONObject getAcountRepaymentListById(String jsonData) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("id");
        List<JSONObject> repaymentFQList = new ArrayList<>();
        List<JSONObject> repaymentDKList = new ArrayList<>();
        List<JSONObject> repaymentRZList = new ArrayList<>();
        List<JSONObject> repaymentRZDBList = new ArrayList<>();
        List<JSONObject> repaymentSFList = new ArrayList<>();
        List<JSONObject> financingRZList = new JSONArray();
        List<JSONObject> financingRZDBList = new JSONArray();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        repaymentSFList = repaymentDao.getAcountRepaymentList(mainId, "3");
        repaymentDKList = repaymentDao.getAcountRepaymentList(mainId, "1");
        repaymentFQList = repaymentDao.getAcountRepaymentList(mainId, "0");
        repaymentRZList = repaymentDao.getAcountRepaymentList(mainId, "2");
        repaymentRZDBList = repaymentDao.getAcountRepaymentList(mainId, "4");
        financingRZList = financingDao.getJSONListByCondition(" AND PARENT_ID='0' AND MAIN_ID=? AND TYPE=2 ORDER BY SORT_NO", new Object[]{mainId});
        financingRZDBList = financingDao.getJSONListByCondition(" AND PARENT_ID='0' AND MAIN_ID=? AND TYPE=4 ORDER BY SORT_NO", new Object[]{mainId});
        if (null != repaymentSFList && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                JSONObject repaymentSFEntity = repaymentSFList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentSFEntity.getString("id")});
                repaymentSFEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentSFEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentDKList && repaymentDKList.size() > 0) {
            for (int i = 0; i < repaymentDKList.size(); i++) {
                JSONObject repaymentDKEntity = repaymentDKList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentDKEntity.getString("id")});
                repaymentDKEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentDKEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentFQList && repaymentFQList.size() > 0) {
            for (int i = 0; i < repaymentFQList.size(); i++) {
                JSONObject repaymentFQEntity = repaymentFQList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentFQEntity.getString("id")});
                repaymentFQEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentFQEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentRZList && repaymentRZList.size() > 0) {
            for (int i = 0; i < repaymentRZList.size(); i++) {
                JSONObject repaymentRZEntity = repaymentRZList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentRZEntity.getString("id")});
                repaymentRZEntity.put("repaymentParentList", repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZEntity, repaymentParentList, "0");
                }
            }
        }
        if (null != repaymentRZDBList && repaymentRZDBList.size() > 0) {
            for (int i = 0; i < repaymentRZDBList.size(); i++) {
                JSONObject repaymentRZDBEntity = repaymentRZDBList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentRZDBEntity.getString("id")});
                repaymentRZDBEntity.put("repaymentParentList", repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZDBEntity, repaymentParentList, "0");
                }
            }

        }

        if (null != financingRZList && financingRZList.size() > 0) {
            for (int i = 0; i < financingRZList.size(); i++) {
                JSONObject financingEntity = financingRZList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) financingDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getString("id")});
                financingEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }
        if (null != financingRZDBList && financingRZDBList.size() > 0) {
            for (int i = 0; i < financingRZDBList.size(); i++) {
                JSONObject financingEntity = financingRZDBList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) financingDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=4  order by SORT_NO", new Object[]{financingEntity.getString("id")});
                financingEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }
        JSONObject result = new JSONObject();
        result.put("main", contractMainEntity);
        result.put("repaymentFQList", repaymentFQList);
        result.put("repaymentDKList", repaymentDKList);
        result.put("repaymentRZList", repaymentRZList);
        result.put("repaymentRZDBList", repaymentRZDBList);
        result.put("repaymentSFList", repaymentSFList);
        result.put("financingRZList", financingRZList);
        result.put("financingRZDBList", financingRZDBList);
        return result;

    }

    //计算剩余欠款逾期罚息 JSON 销售合同
    public void calRemainingArrears(JSONObject jsonObject, List<JSONObject> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal autalRepay = jsonObject.getBigDecimal("repaymentAmount");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        jsonObject.put("remainingArrears", new BigDecimal(0));
        jsonObject.put("overduePenalty", new BigDecimal(0));
        if (repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).put("remainingArrears", new BigDecimal(0));
                repaymentParentList.get(j).put("overduePenalty", new BigDecimal(0));
                if (repaymentParentList.get(j).getInteger("HKType") != 2) {
                    autalRepay = repaymentParentList.get(j).getBigDecimal("repaymentAmount").add(autalRepay);
                }
            }
            if (between_days(jsonObject.getString("repaymentDate"), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay) : new BigDecimal(0));
                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("total").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("total").subtract(autalRepay) : new BigDecimal(0));
                }
            }
        } else {
            if (between_days(jsonObject.getString("repaymentDate"), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay) : new BigDecimal(0));

                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("total").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("total").subtract(autalRepay) : new BigDecimal(0));
                }
            }
        }
        //先算剩余欠款
        jsonObject.put("remainingArrears", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("sumqkmoney", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        //根据剩余欠款算逾期罚息
        calOverduePenalty(jsonObject, repaymentParentList, type);
    }

    public void calOverduePenalty(JSONObject jsonObject, List<JSONObject> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //约定还款日期
        String repaymentDate = jsonObject.getString("repaymentDate");
        //约定还款金额
        BigDecimal repayMentMoney = null;
        //获取冲抵罚息
        BigDecimal cdOverdue = jsonObject.getBigDecimal("cdOverduePenalty");
        if (type.equals("0")) {
            repayMentMoney = jsonObject.getBigDecimal("contractRepaymentAmount");
        } else {
            repayMentMoney = jsonObject.getBigDecimal("total");
        }
        String nowDate = sdf.format(new Date());
        //剩余总欠款
        BigDecimal remainingArrears = jsonObject.getBigDecimal("remainingArrears");
        //最后实际还款日期
        String lastActualRepaymentDate = nowDate;
        BigDecimal overduePenalty = new BigDecimal(0.00);

        BigDecimal everyRemainingArrear = new BigDecimal(0.00);

        //判断剩余欠款的实际还款有几条
        int sumRepay = 0;
        BigDecimal yhOver = new BigDecimal(0.00);
        ;
        //判断主的是逾期罚息还是剩余欠款
        if (jsonObject.getInteger("hkType") != 2) {
            sumRepay = sumRepay + 1;
            everyRemainingArrear = everyRemainingArrear.add(jsonObject.getBigDecimal("repaymentAmount"));
            if (StringUtils.isNotEmpty(jsonObject.getString("actualRepaymentDate"))) {
                lastActualRepaymentDate = jsonObject.getString("actualRepaymentDate");

            }
        } else {
            yhOver = yhOver.add(jsonObject.getBigDecimal("repaymentAmount"));
        }
        //主的剩余欠款
        jsonObject.put("everyRemainingArrear", repayMentMoney.subtract(everyRemainingArrear));
        int jsOverdue = 0;
        //判断是否计算逾期
        if (between_days(repaymentDate, nowDate) > 0) {
            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款
            if (null != repaymentParentList && repaymentParentList.size() > 0) {

                int sumQkHk = 0;
                for (int i = 0; i < repaymentParentList.size(); i++) {
                    if (repaymentParentList.get(i).getInteger("hkType") != 2) {
                        sumRepay = sumRepay + 1;
                        sumQkHk = i;
                        //计算每期剩余欠款,便于计算每期的逾期罚息
                        everyRemainingArrear = everyRemainingArrear.add(repaymentParentList.get(i).getBigDecimal("repaymentAmount"));
                    }
                    repaymentParentList.get(i).put("everyRemainingArrear", repayMentMoney.subtract(everyRemainingArrear));
                }
                //实际还款为欠款还款的最后一条的日期
                lastActualRepaymentDate = repaymentParentList.get(sumQkHk).getString("actualRepaymentDate");
            }
            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款
            if (between_days(lastActualRepaymentDate, repaymentDate) > 0 || StringUtils.isBlank(jsonObject.getString("actualRepaymentDate"))) {
                //（当前日期-约定日期）*总剩余欠款*0.0007
                overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(repaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                //其他为0，最后一条为逾期罚息
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    for (int i = 0; i < repaymentParentList.size(); i++) {
                        repaymentParentList.get(i).put("everyOverduePenalty", new BigDecimal(0.00));
                    }
                } else {
                    jsonObject.put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            } else {
                //判断计算罚息的期数是否包含主的，如果包含，主的为（本期-约定）*上期欠款*0.0007，其他期数为（本期-上期）
                if (between_days(repaymentDate, jsonObject.getString("actualRepaymentDate")) > 0) {
                    jsOverdue = jsOverdue + 1;
                    overduePenalty = overduePenalty.add(repayMentMoney.multiply(
                            new BigDecimal(between_days(repaymentDate, jsonObject.getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //如果还款只有一条并且是主的，那么就加上最后的那个计算
                    if (sumRepay == 1) {
                        //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                        overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    //主的的罚息

                    jsonObject.put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                }
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    if (jsOverdue == 1) {
                        //主的计算
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            repaymentParentList.get(i).put("everyOverduePenalty", new BigDecimal(0.00));
                            if (repaymentParentList.get(i).getInteger("hkType") == 2) {
                                yhOver = yhOver.add(repaymentParentList.get(i).getBigDecimal("repaymentAmount"));
                            }
                            if (between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) > 0) {
                                //判断是否是多期,其他期数为（本期-上期）*上期欠款*0.0007

                                if (i == 0) {
                                    //i==0;本期-主的
                                    overduePenalty = overduePenalty.add(jsonObject.getBigDecimal("everyRemainingArrear").multiply(
                                            new BigDecimal(between_days(jsonObject.getString("actualRepaymentDate"), repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                                } else {
                                    //获取上一期不是逾期罚息的那一期
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getInteger("hkType") != 2) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getBigDecimal("everyRemainingArrear").multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getString("actualRepaymentDate"), repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                            }
                        }
                    } else {
                        //主的不进行计算逾期
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            repaymentParentList.get(i).put("everyOverduePenalty", new BigDecimal(0.00));
                            if (repaymentParentList.get(i).getInteger("hkType") == 2) {
                                yhOver = yhOver.add(repaymentParentList.get(i).getBigDecimal("repaymentAmount"));
                            }
                            if (between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) > 0) {
                                //计算的第一期为（本期-约定）*本期欠款*0.0007，其他期数为（本期-上期）
                                jsOverdue = jsOverdue + 1;
                                if (jsOverdue == 1) {
                                    if (i == 0) {
                                        //上期欠款为主的
                                        overduePenalty = overduePenalty.add(jsonObject.getBigDecimal("everyRemainingArrear").multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);

                                        repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                                    } else {
                                        int qkDate = 0;
                                        for (int j = i - 1; j >= 0; j--) {
                                            if (repaymentParentList.get(j).getInteger("hkType") != 2) {
                                                qkDate = j;
                                                break;
                                            }
                                        }
                                        overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getBigDecimal("everyRemainingArrear").multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                                    }
                                } else {
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getInteger("hkType") != 2) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getBigDecimal("everyRemainingArrear").multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getString("actualRepaymentDate"), repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007)));
                                    repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                                }
                            }
                        }
                    }
                    //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                    overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    repaymentParentList.get(repaymentParentList.size() - 1).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                }
            }

        }
        //最终罚息
        jsonObject.put("sumyqmoney", overduePenalty.subtract(cdOverdue).setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("overduePenalty", overduePenalty.subtract(cdOverdue).setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("overduePenaltyTotal", overduePenalty.setScale(2, BigDecimal.ROUND_HALF_UP));
    }


    //计算剩余欠款逾期罚息 实体 销售合同
    public void calRemainingArrears(RepaymentEntity jsonObject, List<RepaymentEntity> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        BigDecimal autalRepay = jsonObject.getRepaymentAmount();
        if (null != repaymentParentList && repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).setRemainingArrears(new BigDecimal(0));
                repaymentParentList.get(j).setOverduePenalty(new BigDecimal(0));
                if (repaymentParentList.get(j).getHkType() != 2) {
                    autalRepay = repaymentParentList.get(j).getRepaymentAmount().add(autalRepay);
                }
            }
            if (between_days(jsonObject.getRepaymentDate(), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getContractRepaymentAmount().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getContractRepaymentAmount().subtract(autalRepay) : new BigDecimal(0));
                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getTotal().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getTotal().subtract(autalRepay) : new BigDecimal(0));
                }
            }
        } else {
            if (between_days(jsonObject.getRepaymentDate(), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getContractRepaymentAmount().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getContractRepaymentAmount().subtract(autalRepay) : new BigDecimal(0));

                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getTotal().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getTotal().subtract(autalRepay) : new BigDecimal(0));
                }
            }
        }
        //先算剩余欠款
        jsonObject.setRemainingArrears(sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        //根据剩余欠款算逾期罚息
        calOverduePenalty(jsonObject, repaymentParentList, type);

    }

    public void calOverduePenalty(RepaymentEntity jsonObject, List<RepaymentEntity> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //约定还款日期
        String repaymentDate = jsonObject.getRepaymentDate();
        //约定还款金额
        BigDecimal repayMentMoney = null;
        //获取冲抵罚息
        BigDecimal cdOverdue = jsonObject.getCdOverduePenalty();
        if (type.equals("0")) {
            repayMentMoney = jsonObject.getContractRepaymentAmount();
        } else {
            repayMentMoney = jsonObject.getTotal();
        }
        String nowDate = sdf.format(new Date());
        //剩余总欠款
        BigDecimal remainingArrears = jsonObject.getRemainingArrears();
        //最后实际还款日期
        String lastActualRepaymentDate = repaymentDate;
        BigDecimal overduePenalty = new BigDecimal(0.00);

        BigDecimal everyRemainingArrear = new BigDecimal(0.00);
        //判断剩余欠款的实际还款有几条
        int sumRepay = 0;
        //判断主的是逾期罚息还是剩余欠款
        if (jsonObject.getHkType() != 2) {
            sumRepay = sumRepay + 1;
            everyRemainingArrear = everyRemainingArrear.add(jsonObject.getRepaymentAmount());
            if (StringUtils.isNotEmpty(jsonObject.getActualRepaymentDate())) {
                lastActualRepaymentDate = jsonObject.getActualRepaymentDate();

            }
        }
        //主的剩余欠款
        //主的剩余欠款
        jsonObject.setEveryRemainingArrear(repayMentMoney.subtract(everyRemainingArrear));
        int jsOverdue = 0;
        //判断是否计算逾期
        if (between_days(repaymentDate, nowDate) > 0) {
            //判断实际还款有几条
            if (null != repaymentParentList && repaymentParentList.size() > 0) {

                int sumQkHk = 0;
                for (int i = 0; i < repaymentParentList.size(); i++) {
                    if (repaymentParentList.get(i).getHkType() != 2) {
                        sumRepay = sumRepay + 1;
                        sumQkHk = i;
                        //计算每期剩余欠款,便于计算每期的逾期罚息
                        everyRemainingArrear = everyRemainingArrear.add(repaymentParentList.get(i).getRepaymentAmount());
                    }
                    repaymentParentList.get(i).setEveryRemainingArrear(repayMentMoney.subtract(everyRemainingArrear));
                }
                //实际还款为欠款还款的最后一条的日期
                lastActualRepaymentDate = repaymentParentList.get(sumQkHk).getActualRepaymentDate();
            }
            //判断实际还款有几条，只有一条 或者没有(当前日期-约定日期)*0.0007*总剩余欠款
            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款
            if (between_days(lastActualRepaymentDate, repaymentDate) > 0) {
                //（当前日期-约定日期）*总剩余欠款*0.0007
                overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(repaymentDate, nowDate) * 0.0007)));
            } else {
                //判断计算罚息的有几期
                //判断计算罚息的期数是否包含主的，如果包含，主的为（本期-约定）*上期欠款*0.0007，其他期数为（本期-上期）
                if (between_days(repaymentDate, jsonObject.getActualRepaymentDate()) > 0) {
                    jsOverdue = jsOverdue + 1;
                    overduePenalty = overduePenalty.add(repayMentMoney.multiply(
                            new BigDecimal(between_days(repaymentDate, jsonObject.getActualRepaymentDate()) * 0.0007)));
                }
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    if (jsOverdue == 1) {
                        //主的计算
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            if (between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) > 0) {
                                //判断是否是多期,其他期数为（本期-上期）*上期欠款*0.0007
                                if (i == 0) {
                                    //i==0;本期-主的
                                    overduePenalty = overduePenalty.add(jsonObject.getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(jsonObject.getActualRepaymentDate(), repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007)));
                                } else {
                                    //获取上一期不是逾期罚息的那一期
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getHkType() != 2) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getActualRepaymentDate(), repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007)));
                                }
                            }
                        }
                    } else {
                        //主的不进行计算逾期
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            if (between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) > 0) {
                                //计算的第一期为（本期-约定）*本期欠款*0.0007，其他期数为（本期-上期）
                                jsOverdue = jsOverdue + 1;
                                if (jsOverdue == 1) {
                                    if (i == 0) {
                                        //上期欠款为主的
                                        overduePenalty = overduePenalty.add(jsonObject.getEveryRemainingArrear().multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007)));
                                    } else {
                                        int qkDate = 0;
                                        for (int j = i - 1; j >= 0; j--) {
                                            if (repaymentParentList.get(j).getHkType() != 2) {
                                                qkDate = j;
                                                break;
                                            }
                                        }
                                        overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007)));
                                    }
                                } else {
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getHkType() != 2) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getActualRepaymentDate(), repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007)));
                                }
                            }
                        }
                    }

                }
                //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007)));
            }

        }
        //最终罚息
        jsonObject.setOverduePenalty(overduePenalty.subtract(cdOverdue).setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.setOverduePenaltyTotal(overduePenalty.setScale(2, BigDecimal.ROUND_HALF_UP));
    }

    //计算剩余欠款逾期罚息 JSON 融资合同
    public void calRemainingArrears(JSONObject jsonObject, List<JSONObject> repaymentParentList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal autalRepay = jsonObject.getBigDecimal("advancesMoney");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        jsonObject.put("remainingArrears", new BigDecimal(0.00));
        if (repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).put("remainingArrears", new BigDecimal(0));
                autalRepay = repaymentParentList.get(j).getBigDecimal("advancesMoney").add(autalRepay);
            }
            if (between_days(jsonObject.getString("financingDate"), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("financingMoney")
                        .subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ?
                        jsonObject.getBigDecimal("financingMoney").subtract(autalRepay)
                        : new BigDecimal(0));
            }
        } else {
            if (between_days(jsonObject.getString("financingDate"), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("financingMoney")
                        .subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ?
                        jsonObject.getBigDecimal("financingMoney").subtract(autalRepay) : new BigDecimal(0));
            }
        }

        //先算剩余欠款
        jsonObject.put("remainingArrears", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("sumqkmoney", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        //根据剩余欠款算逾期罚息
        jsonObject.put("sumyqmoney", sumyqmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("overduePenalty", sumyqmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
    }

    //计算剩余欠款逾期罚息 实体  融资合同
    public void calRemainingArrears(FinancingEntity jsonObject, List<FinancingEntity> repaymentParentList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        BigDecimal autalRepay = jsonObject.getAdvancesMoney();

        if (repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).setRemainingArrears(new BigDecimal(0));
                autalRepay = repaymentParentList.get(j).getAdvancesMoney().add(autalRepay);
            }
            if (between_days(jsonObject.getFinancingDate(), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getFinancingMoney().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getFinancingMoney().subtract(autalRepay) : new BigDecimal(0));
            }
        } else {
            if (between_days(jsonObject.getFinancingDate(), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getFinancingMoney().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getFinancingMoney().subtract(autalRepay) : new BigDecimal(0));
            }
        }
        //先算剩余欠款
        jsonObject.setRemainingArrears(sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
    }

    //保存逾期罚款明细
    public void saveOverDueDetail(String mainId, String startTime, String endTime, BigDecimal overduePenaltyAmount) {

        OverDueDetail overDueDetail = new OverDueDetail();
        overDueDetail.setMainId(mainId);
        overDueDetail.setOverduePenaltyAmount(overduePenaltyAmount);
        overDueDetail.setStartTime(startTime);
        overDueDetail.setEndTime(endTime);
        overDueDetailDao.add(overDueDetail);

    }

    //保存冲抵list
    @Override
    public JSONObject saveAcountRepaymentListById(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONArray repaymentFQList = new JSONArray();
        JSONArray repaymentDKList = new JSONArray();
        JSONArray repaymentRZList = new JSONArray();
        JSONArray repaymentRZDBList = new JSONArray();
        JSONArray financingRZList = new JSONArray();
        JSONArray financingRZDBList = new JSONArray();
        JSONArray repaymentSFList = new JSONArray();
        JSONObject main = JSON.parseObject(jsonPalams.getString("main"));
        String repayDate = jsonPalams.getString("repayDate");
        String createUserId = jsonPalams.getString("createUserId");
        String createUserName = jsonPalams.getString("createUserName");
        String nowDate = DateUtils.nowDayByString(contractMainDao.getCurrentTime());
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(main.getString("id"));
        contractMainEntity.setAccountBalance(jsonPalams.getBigDecimal("canUseMoney"));
        if (contractMainEntity.getHaveOverdue() != 2) {
            contractMainEntity.setHaveOverdue(0);
            contractMainEntity.setHaveOverdueNo(-6);
        }
        contractMainDao.update(contractMainEntity);
        repaymentFQList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentFQList"));
        repaymentDKList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentDKList"));
        repaymentRZList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentRZList"));
        repaymentRZDBList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentRZDBList"));
        repaymentSFList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentSFList"));
        financingRZList = JSONArray.fromObject(jsonPalams.getJSONArray("financingRZList"));
        financingRZDBList = JSONArray.fromObject(jsonPalams.getJSONArray("financingRZDBList"));
        Integer havaDsdf = contractMainEntity.getHaveDsdf();
        saveRepaymentList(repaymentFQList, repayDate, createUserId, createUserName, 0, nowDate);
        saveRepaymentList(repaymentDKList, repayDate, createUserId, createUserName, 1, nowDate);
        saveRepaymentList(repaymentSFList, repayDate, createUserId, createUserName, 3, nowDate);
        if (havaDsdf != 0) {
            saveRepaymentList(repaymentRZList, repayDate, createUserId, createUserName, 2, nowDate);
            saveRepaymentList(repaymentRZDBList, repayDate, createUserId, createUserName, 4, nowDate);
        }
        saveFinancingList(financingRZList, repayDate, createUserId, createUserName, 2, nowDate);
        saveFinancingList(financingRZDBList, repayDate, createUserId, createUserName, 4, nowDate);
        JSONObject result = new JSONObject();
        result.put("true", "true");
        return result;

    }

    public void saveFinancingList(JSONArray repaymentList, String repayDate, String createUserId, String createUserName, Integer type, String nowDate) {
        if (null != repaymentList && repaymentList.size() > 0) {
            for (int i = 0; i < repaymentList.size(); i++) {
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                net.sf.json.JSONObject FQJson = repaymentList.getJSONObject(i);
                BigDecimal qkRepayment = new BigDecimal(FQJson.getString("qkRepayment"));
                BigDecimal jrPenalty = new BigDecimal(FQJson.getString("jrPenalty"));
                BigDecimal yqRepayment = new BigDecimal(FQJson.getString("yqRepayment"));

                FinancingEntity financingEntity = (FinancingEntity) financingDao.getIBaseEntityById(FQJson.getString("id"));
                financingEntity.setRemainingArrears(new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment).compareTo(
                        new BigDecimal(0.00)) > 0 ? new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment) : new BigDecimal(0.00)
                );
                financingEntity.setJroverduePenalty(new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment).compareTo(
                        new BigDecimal(0.00)) > 0 ? new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment) : new BigDecimal(0.00)
                );
                financingEntity.setJrPenalty(jrPenalty.add(yqRepayment));
                financingEntity.setRemark(FQJson.getString("remark"));
                financingEntity.setRepaymentAttachName(FQJson.getString("repaymentAttachName"));
                financingEntity.setRepaymentAttachUrl(FQJson.getString("repaymentAttachUrl"));
                financingDao.update(financingEntity);
                yqSum = yqSum.add(financingEntity.getAdvancesMoney());
                dateTime = financingEntity.getAdvancesDate();
                //获取子list
                JSONArray repaymentParentList = new JSONArray();
                repaymentParentList = FQJson.getJSONArray("repaymentParentList");
                for (int j = 0; j < repaymentParentList.size(); j++) {
                    FinancingEntity repaymentParentEntity = (FinancingEntity) financingDao.getIBaseEntityById(repaymentParentList.getJSONObject(j).getString("id"));
                    if (null != repaymentParentEntity) {
                        repaymentParentEntity.setRemainingArrears(new BigDecimal(0.00));
                        repaymentParentEntity.setRemark(repaymentParentList.getJSONObject(j).getString("remark"));
                        repaymentParentEntity.setRepaymentAttachName(repaymentParentList.getJSONObject(j).getString("repaymentAttachName"));
                        repaymentParentEntity.setRepaymentAttachUrl(repaymentParentList.getJSONObject(j).getString("repaymentAttachUrl"));
                        repaymentDao.update(repaymentParentEntity);
                        yqSum = yqSum.add(repaymentParentEntity.getAdvancesMoney());
                        dateTime = repaymentParentEntity.getAdvancesDate();
                    }

                }

                if (qkRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    FinancingEntity financingEntityHK = (FinancingEntity) financingDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(financingEntityHK.getAdvancesDate()) && financingEntityHK.getAdvancesMoney().compareTo(new BigDecimal(0.00)) == 0) {
                        financingEntityHK.setAdvancesDate(repayDate);
                        financingEntityHK.setAdvancesMoney(qkRepayment);
                        financingEntityHK.setHkType(1);
                        financingEntityHK.setType(type);
                        financingEntityHK.setCreateUserId(createUserId);
                        financingEntityHK.setCreateUserName(createUserName);
                        financingEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.update(financingEntityHK);
                    } else {
                        //查询跟踪款
                        List<FinancingEntity> repaymentParentListHK = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        FinancingEntity financingEntityParentHK = new FinancingEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            financingEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            financingEntityParentHK.setSortNo(0);
                        }
                        financingEntityParentHK.setMainId(FQJson.getString("mainId"));
                        financingEntityParentHK.setParentId(FQJson.getString("id"));
                        financingEntityParentHK.setFinancingDate(FQJson.getString("financingDate"));
                        financingEntityParentHK.setFinancingMoney(new BigDecimal(FQJson.getString("financingMoney")));
                        financingEntityParentHK.setAdvancesDate(repayDate);
                        financingEntityParentHK.setAdvancesMoney(qkRepayment);
                        financingEntityParentHK.setHkType(1);
                        financingEntityParentHK.setType(type);
                        financingEntityParentHK.setCreateUserId(createUserId);
                        financingEntityParentHK.setCreateUserName(createUserName);
                        financingEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.add(financingEntityParentHK);
                    }
                }
                if (yqRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    FinancingEntity financingEntityHK = (FinancingEntity) financingDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(financingEntityHK.getAdvancesDate()) && financingEntityHK.getAdvancesMoney().compareTo(new BigDecimal(0.00)) == 0) {
                        financingEntityHK.setAdvancesDate(repayDate);
                        financingEntityHK.setAdvancesMoney(qkRepayment.add(yqRepayment));
                        financingEntityHK.setHkType(2);
                        financingEntityHK.setRemark(FQJson.getString("remark") + "逾期罚息还款" + yqRepayment + "元");
                        financingEntityHK.setType(type);
                        financingEntityHK.setCreateUserId(createUserId);
                        financingEntityHK.setCreateUserName(createUserName);
                        financingEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.update(financingEntityHK);
                    } else {
                        //查询跟踪款
                        List<FinancingEntity> repaymentParentListHK = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        FinancingEntity financingEntityParentHK = new FinancingEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            financingEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            financingEntityParentHK.setSortNo(0);
                        }
                        financingEntityParentHK.setMainId(FQJson.getString("mainId"));
                        financingEntityParentHK.setParentId(FQJson.getString("id"));
                        financingEntityParentHK.setFinancingDate(FQJson.getString("financingDate"));
                        financingEntityParentHK.setFinancingMoney(new BigDecimal(FQJson.getString("financingMoney")));
                        financingEntityParentHK.setAdvancesDate(repayDate);
                        financingEntityParentHK.setAdvancesMoney(yqRepayment);
                        financingEntityParentHK.setHkType(2);
                        financingEntityParentHK.setRemark("逾期罚息还款" + yqRepayment + "元");
                        financingEntityParentHK.setType(type);
                        financingEntityParentHK.setCreateUserId(createUserId);
                        financingEntityParentHK.setCreateUserName(createUserName);
                        financingEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.add(financingEntityParentHK);
                    }
                }

                //判断逾期
                if (financingEntity.getFinancingDate().compareTo(nowDate) <= 0) {
                    getOverDue(FQJson.getString("mainId"), yqSum, dateTime, financingEntity.getFinancingMoney(), financingEntity.getFinancingDate(), nowDate);
                }
            }
        }
    }

    public void saveRepaymentList(JSONArray repaymentList, String repayDate, String createUserId, String createUserName, Integer type, String nowDate) {
        if (null != repaymentList && repaymentList.size() > 0) {
            for (int i = 0; i < repaymentList.size(); i++) {
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                net.sf.json.JSONObject FQJson = repaymentList.getJSONObject(i);
                BigDecimal qkRepayment = new BigDecimal(FQJson.getString("qkRepayment"));
                BigDecimal yqRepayment = new BigDecimal(FQJson.getString("yqRepayment"));
                BigDecimal gsPenalty = new BigDecimal(FQJson.getString("gsPenalty"));
                RepaymentEntity repaymentEntity = (RepaymentEntity) repaymentDao.getIBaseEntityById(FQJson.getString("id"));
                repaymentEntity.setOverduePenalty(new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment).compareTo(new BigDecimal(0.00)) > 0 ?
                        new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment) : new BigDecimal(0.00));
                repaymentEntity.setRemainingArrears(new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment).compareTo(new BigDecimal(0.00)) > 0 ?
                        new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment) : new BigDecimal(0.00));
                repaymentEntity.setCdRemainingArrears(qkRepayment.add(repaymentEntity.getCdRemainingArrears()));
                repaymentEntity.setCdOverduePenalty(yqRepayment.add(repaymentEntity.getCdOverduePenalty()));
                repaymentEntity.setOverduePenaltyTotal(new BigDecimal(FQJson.getString("overduePenaltyTotal")));
                repaymentEntity.setRemark(FQJson.getString("remark"));
                repaymentEntity.setGsPenalty(gsPenalty.add(yqRepayment));
                repaymentEntity.setRepaymentAttachName(FQJson.getString("repaymentAttachName"));
                repaymentEntity.setRepaymentAttachUrl(FQJson.getString("repaymentAttachUrl"));
                repaymentDao.update(repaymentEntity);
                yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                dateTime = repaymentEntity.getActualRepaymentDate();
                //获取子list
                JSONArray repaymentParentList = new JSONArray();
                repaymentParentList = FQJson.getJSONArray("repaymentParentList");
                for (int j = 0; j < repaymentParentList.size(); j++) {
                    RepaymentEntity repaymentParentEntity = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentParentList.getJSONObject(j).getString("id"));
                    if (null != repaymentParentEntity) {
                        repaymentParentEntity.setRemainingArrears(new BigDecimal(0.00));
                        repaymentParentEntity.setOverduePenalty(new BigDecimal(0.00));
                        repaymentParentEntity.setRemark(repaymentParentList.getJSONObject(j).getString("remark"));
                        repaymentParentEntity.setRepaymentAttachName(repaymentParentList.getJSONObject(j).getString("repaymentAttachName"));
                        repaymentParentEntity.setRepaymentAttachUrl(repaymentParentList.getJSONObject(j).getString("repaymentAttachUrl"));
                        repaymentDao.update(repaymentParentEntity);
                        yqSum = yqSum.add(repaymentParentEntity.getRepaymentAmount());
                        dateTime = repaymentParentEntity.getActualRepaymentDate();
                    }
                }
                if (qkRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    RepaymentEntity repaymentEntityHK = (RepaymentEntity) repaymentDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(repaymentEntityHK.getActualRepaymentDate()) && repaymentEntityHK.getRepaymentAmount().compareTo(new BigDecimal(0.00)) == 0) {
                        repaymentEntityHK.setActualRepaymentDate(repayDate);
                        repaymentEntityHK.setRepaymentAmount(qkRepayment);
                        repaymentEntityHK.setHkType(1);
                        repaymentEntityHK.setCreateUserId(createUserId);
                        repaymentEntityHK.setType(type);
                        repaymentEntityHK.setCreateUserName(createUserName);
                        repaymentEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentDao.update(repaymentEntityHK);
                    } else {
                        //查询跟踪款
                        List<RepaymentEntity> repaymentParentListHK = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        RepaymentEntity repaymentEntityParentHK = new RepaymentEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            repaymentEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            repaymentEntityParentHK.setSortNo(0);
                        }
                        repaymentEntityParentHK.setMainId(FQJson.getString("mainId"));
                        repaymentEntityParentHK.setHkType(1);
                        repaymentEntityParentHK.setType(type);
                        repaymentEntityParentHK.setParentId(FQJson.getString("id"));
                        repaymentEntityParentHK.setRepaymentDate(FQJson.getString("repaymentDate"));
                        repaymentEntityParentHK.setRepaymentAmount(qkRepayment);
                        repaymentEntityParentHK.setRemainingArrears(new BigDecimal(0.00));
                        repaymentEntityParentHK.setOverduePenalty(new BigDecimal(0.00));
                        repaymentEntityParentHK.setActualRepaymentDate(repayDate);
                        repaymentEntityParentHK.setTotal(new BigDecimal(FQJson.getString("total")));
                        repaymentEntityParentHK.setPrincipal(new BigDecimal(FQJson.getString("principal")));
                        repaymentEntityParentHK.setInterest(new BigDecimal(FQJson.getString("interest")));
                        repaymentEntityParentHK.setContractRepaymentAmount(new BigDecimal(FQJson.getString("contractRepaymentAmount")));
                        repaymentEntityParentHK.setCreateUserId(createUserId);
                        repaymentEntityParentHK.setCreateUserName(createUserName);
                        repaymentEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentDao.add(repaymentEntityParentHK);
                        yqSum = yqSum.add(repaymentEntityParentHK.getRepaymentAmount());
                        dateTime = repaymentEntityParentHK.getActualRepaymentDate();
                    }
                }
                if (yqRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    RepaymentEntity repaymentEntityHK = (RepaymentEntity) repaymentDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(repaymentEntityHK.getActualRepaymentDate()) && repaymentEntityHK.getRepaymentAmount().compareTo(new BigDecimal(0.00)) == 0) {
                        repaymentEntityHK.setActualRepaymentDate(repayDate);
                        repaymentEntityHK.setRepaymentAmount(yqRepayment);
                        repaymentEntityHK.setCreateUserId(createUserId);
                        repaymentEntityHK.setType(type);
                        repaymentEntityHK.setCreateUserName(createUserName);
                        repaymentEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentEntityHK.setHkType(2);
                        repaymentEntityHK.setRemark(FQJson.getString("remark") + "逾期罚息还款" + yqRepayment + "元");
                        repaymentDao.update(repaymentEntityHK);
                    } else {
                        //查询跟踪款
                        List<RepaymentEntity> repaymentParentListHK = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        RepaymentEntity repaymentEntityParentHK = new RepaymentEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            repaymentEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            repaymentEntityParentHK.setSortNo(0);
                        }
                        repaymentEntityParentHK.setHkType(2);
                        repaymentEntityParentHK.setMainId(FQJson.getString("mainId"));
                        repaymentEntityParentHK.setType(type);
                        repaymentEntityParentHK.setParentId(FQJson.getString("id"));
                        repaymentEntityParentHK.setRepaymentDate(FQJson.getString("repaymentDate"));
                        repaymentEntityParentHK.setRepaymentAmount(yqRepayment);
                        repaymentEntityParentHK.setRemark("逾期罚息还款" + yqRepayment + "元");
                        repaymentEntityParentHK.setRemainingArrears(new BigDecimal(0.00));
                        repaymentEntityParentHK.setOverduePenalty(new BigDecimal(0.00));
                        repaymentEntityParentHK.setActualRepaymentDate(repayDate);
                        repaymentEntityParentHK.setTotal(new BigDecimal(FQJson.getString("total")));
                        repaymentEntityParentHK.setPrincipal(new BigDecimal(FQJson.getString("principal")));
                        repaymentEntityParentHK.setInterest(new BigDecimal(FQJson.getString("interest")));
                        repaymentEntityParentHK.setContractRepaymentAmount(new BigDecimal(FQJson.getString("contractRepaymentAmount")));
                        repaymentEntityParentHK.setCreateUserId(createUserId);
                        repaymentEntityParentHK.setCreateUserName(createUserName);
                        repaymentEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentDao.add(repaymentEntityParentHK);
                        yqSum = yqSum.add(repaymentEntityParentHK.getRepaymentAmount());
                        dateTime = repaymentEntityParentHK.getActualRepaymentDate();
                    }
                }
                //判断逾期
                if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                    if (repaymentEntity.getType() == 2 || repaymentEntity.getType() == 4) {
                        getOverDue(FQJson.getString("mainId"), yqSum, dateTime, repaymentEntity.getContractRepaymentAmount(), repaymentEntity.getRepaymentDate(), nowDate);
                    } else {
                        getOverDue(FQJson.getString("mainId"), yqSum, dateTime, repaymentEntity.getTotal(), repaymentEntity.getRepaymentDate(), nowDate);

                    }
                }
            }
        }
    }

    //宇哥新机出库
    @Override
    public JSONObject selectContractList(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        //String userId = json.getString("userId");
        String modelName = json.getString("modelName");
        StringBuilder condition = new StringBuilder();
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(json.getString("pageSize"))) {
            pageSize = json.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(json.getString("requestPage"))) {
            requestPage = json.getInteger("requestPage");
        }
        condition.append("AND t_con_main.MODEL_NAME='" + modelName + "'");
        condition.append(" AND t_con_main.AUDIT_FLAG=1 AND SERIAL_NO is null ");
        List<JSONObject> recordsList = contractMainDao.getListBymodelName(condition.toString(), requestPage, pageSize);
        int recordCount = contractMainDao.getListBymodelName(condition.toString(), 1, Integer.MAX_VALUE).size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", recordsList);
        return result;
    }

    @Override
    public JSONObject selectContractAccountById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String repayDate = jsonParams.getString("repayDate");
        String mainId = jsonParams.getString("mainId");
        String condition = "AND MAIN_ID = '" + mainId + "'\n" +
                "AND (\n" +
                "\tREMAINING_ARREARS IS NOT NULL\n" +
                "\tAND REMAINING_ARREARS != 0.00\n" +
                ")\n" +
                "OR (\n" +
                "\tREPAYMENT_DATE > '" + repayDate + "'\n" +
                "\tAND MAIN_ID = '" + mainId + "'\n" +
                ")\n" +
                "ORDER BY\n" +
                "\tREPAYMENT_DATE";
        List<JSONObject> repaymentList = repaymentDao.getJSONListByCondition(condition, new Object[]{});
        JSONObject result = new JSONObject();
        result.put("repaymentList", repaymentList);
        return result;
    }

    @Override
    public JSONObject updateContractAccountMoney(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String repayDate = jsonParams.getString("repayDate");
        String id = jsonParams.getString("id");
        String type = jsonParams.getString("type");
        if (type.equals("1")) {
            RepaymentEntity newRepaymentEntity = new RepaymentEntity();
            RepaymentEntity repaymentEntity = (RepaymentEntity) repaymentDao.getIBaseEntityById(id);
            newRepaymentEntity.setRepaymentAmount(repaymentEntity.getRemainingArrears());
            newRepaymentEntity.setRepaymentDate(repayDate);
            if (repaymentEntity.getParentId().equals("0")) {
                newRepaymentEntity.setParentId(repaymentEntity.getId());
            }
            ;
            repaymentEntity.setRemainingArrears(new BigDecimal(0.00));
            repaymentDao.update(repaymentEntity);
//            repaymentDao.add()

        } else {

        }

        return null;
    }

    //应收保存方法
    @Override
    public JSONObject receivable(String jsonData) {
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//买卖双方及担保方信息
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资分期
        List<FinancingEntity> financingRZEntityList = model.getFinancingRZList();//融资分期款跟踪
        List<FinancingEntity> financingRZDBEntityList = model.getFinancingRZDBList();//融资分期款跟踪
        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资分期
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        List<RepaymentEntity> repaymentFQFirstList = model.getRepaymentFQFirstList();//首付款信息
        List<CollectionEntity> collectionList = model.getCollectionList();//催款记录

        String mainId = contractMainEntity.getId();//主表的ID
        boolean flag = true;
        //修改合同，先级联删除现有的所有合同，再添加
        repaymentDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        financingDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        collectionDao.removeByCondition("  AND MAIN_ID =?", new String[]{mainId});

        //更新主表信息
        ContractMainEntity mainEntitys = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (mainEntitys.getHaveOverdue() != 2) {
            contractMainEntity.setHaveOverdue(0);
            contractMainEntity.setHaveOverdueNo(-6);
            contractMainDao.update(contractMainEntity);
        }
        String nowDate = DateUtils.nowDateByString(contractMainDao.getCurrentTime());
        //首付款信息(销售台账)
        if (null != repaymentaSFEntityList && repaymentaSFEntityList.size() > 0) {
            for (int i = 0; i < repaymentaSFEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaSFEntityList.get(i);
                //还款日期不为空则添加
                //模块0-内部分期/1-垫款/2-融资分期/3-首付款信息
                repaymentaSFEntityList.get(i).setType(3);
                repaymentaSFEntityList.get(i).setMainId(mainId);
                repaymentaSFEntityList.get(i).setSortNo(i);
                repaymentDao.add(repaymentaSFEntityList.get(i));
                yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                dateTime = repaymentEntity.getActualRepaymentDate();

                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(3);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());
                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {
                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);

                        }
                    }
                }
            }
        }
        //判断是否为垫款->插入分期表
        if (contractMainEntity.getHaveRepayment() == 1) {
            for (int i = 0; i < repaymentaDKEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaDKEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setType(1);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentEntity.getInterest().add(repaymentEntity.getPrincipal()));
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();
                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(1);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();

                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                flag = false;
                                mainEntity.setHaveOverdue(1);
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);

                        }
                    }
                }
            }
        }
        //判断购买方式是否为内部分期->插入分期表
        if (contractMainEntity.getBuyType().equals("内部分期")) {
            for (int i = 0; i < repaymentaFQEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaFQEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(0);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentaFQEntityList.get(i).getInterest().add(repaymentaFQEntityList.get(i).getPrincipal()));
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();

                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(0);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();

                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);

                        }
                    }
                }
            }
        }
        //判断购买方式是否为内部分期 并且有分期首付款分期 ->插入分期表
        if (contractMainEntity.getBuyType().equals("内部分期") && contractMainEntity.getHaveFQFirst() == 1) {

            for (int i = 0; i < repaymentFQFirstList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentFQFirstList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(5);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentFQFirstList.get(i).getPrincipal());
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();

                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(5);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {


                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);
                        }
                    }
                }

            }
        }
        //判断购买方式是否为融资租赁->插入分期表
        if (contractMainEntity.getBuyType().equals("融资租赁")) {
            //融资分期跟踪
            for (int i = 0; i < financingRZEntityList.size(); i++) {
                FinancingEntity financingEntity = financingRZEntityList.get(i);
                if (!StringUtils.isBlank(financingEntity.getFinancingDate())) {
                    financingEntity.setMainId(mainId);
                    financingEntity.setSortNo(i);
                    financingDao.add(financingEntity);
                }
            }
            for (int i = 0; i < repaymentaRZEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaRZEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(2);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();
                }

                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(2);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getContractRepaymentAmount().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);
                        }
                    }
                }
            }
        }
        //判断购买方式是否为融资租赁打包->插入分期表
        if (contractMainEntity.getBuyType().equals("融资租赁打包")) {
            //融资分期跟踪
            for (int i = 0; i < financingRZDBEntityList.size(); i++) {
                FinancingEntity financingEntity = financingRZDBEntityList.get(i);
                if (!StringUtils.isBlank(financingEntity.getFinancingDate())) {
                    financingEntity.setMainId(mainId);
                    financingEntity.setSortNo(i);
                    financingDao.add(financingEntity);
                }
            }
            for (int i = 0; i < repaymentaRZDBEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaRZDBEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(4);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();
                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(4);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                //判断是否逾期
                if (repaymentEntity.getContractRepaymentAmount().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);
                        }
                    }
                }
            }
        }
        //催收记录
        if (null != collectionList && collectionList.size() > 0) {
            for (int i = 0; i < collectionList.size(); i++) {
                CollectionEntity collectionEntity = collectionList.get(i);
                if (StringUtils.isNotEmpty(collectionEntity.getCollection())) {
                    collectionEntity.setMainId(mainId);
                    collectionEntity.setSortNo(i);
                    collectionDao.add(collectionEntity);
                }
            }
        }
        //判断接近还款日期
        String mainIds = "";
        ContractMainEntity mains = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (mains.getHaveOverdue() == 2) {
            List<JSONObject> list = contractMainDao.senderExpireList();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    mainIds += "'" + list.get(i).getString("mainId") + "',";
                }
            }
            if (mainIds.length() > 0) {
                mainIds = mainIds.substring(0, mainIds.length() - 1);
            }
            if (!mainIds.contains(mainId)) {
                mains.setHaveOverdue(0);
                mains.setHaveOverdueNo(-6);
                contractMainDao.update(mains);
            }
        }
        JSONObject result = new JSONObject();
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    //查看客户
    @Override
    public List<JSONObject> getNameAndTel(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String key = jsonParams.getString("key");
        StringBuffer stringBuffer = new StringBuffer();
        if (jsonParams.containsKey("createUserId")) {
            String userId = jsonParams.getString("createUserId");
            String userIds = checkDao.getChilderByUserId(userId, true);//他能看到的人""
            stringBuffer.append(" AND CREATE_USER_ID IN ( " + userIds + " )\n");
        }
        return weekPlanDao.getNameAndTel(" and t_wrt_customer.`NAME` like ?", new Object[]{"%" + key + "%"});
    }

    @Override
    public List<JSONObject> senderExpireList(String jsonData) {
        return contractMainDao.senderExpireList();
    }

    //验证身份证号
    private boolean matchesCard(String matchesCard) {
        if (StringUtils.isBlank(matchesCard)) {
            return false;
        }
        String pattern = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(matchesCard);
        return m.matches();
    }

    private String matchesOdd(String matchesCard) {
        if (StringUtils.isBlank(matchesCard)) {
            return "";
        }
        String pattern = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(matchesCard);
        if (m.matches()) {
            return execute(matchesCard);
        }
        return "";
    }

    public String execute(String value) {
        value = value.trim();
        if (value == null || (value.length() != 15 && value.length() != 18)) {
            return "";
        }
        if (value.length() == 15 || value.length() == 18) {
            String lastValue = value.substring(value.length() - 1, value.length());
            String lastValues = value.substring(value.length() - 2, value.length() - 1);
            int sex;
            if (lastValue.trim().toLowerCase().equals("x") || lastValue.trim().toLowerCase().equals("e")) {
                return "先生";
            } else {
                sex = Integer.parseInt(lastValues) % 2;
                return sex == 0 ? "女士" : "先生";
            }
        } else {
            return "";
        }
    }

    //创建合同时获取区域经理
    @Override
    public List<JSONObject> getRegionManagerByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String key = jsonParams.getString("key");
        String companyId = jsonParams.getString("companyId");
        StringBuffer condition = new StringBuffer();
        List<Object> arrayList = new ArrayList<Object>();
        condition.append("AND v_sys_part_time_for_report.userName LIKE ?  ");
        arrayList.add("%" + key + "%");
        if (!StringUtils.isBlank(companyId)) {
            condition.append("AND t_sys_company.ID = ? ");
            arrayList.add(companyId);
        }
        return contractMainDao.getRegionManagerByUserId(condition.toString(), arrayList.toArray());
    }

    //删除
    @Override
    public Boolean remove(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = json.getString("id");
        //删除置换信息
        List<ReplacementEntity> replacementEntityList = (List<ReplacementEntity>) (Object) replacementDao.getIBaseEntityByCondition(" and main_id=?", new String[]{mainId});
        if (null != replacementEntityList && replacementEntityList.size() > 0) {
            for (ReplacementEntity replacementList : replacementEntityList) {
                deviceDisplaceDao.delByCondition("AND REPLACEMENT_ID = ?", new String[]{replacementList.getId()});
            }
        }
        //修改合同，先级联删除现有的所有合同，再添加
        guarantorDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        replacementDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        repaymentDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        contractSalesDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        auditDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='contractType' ", new String[]{mainId});
        copierDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='contractType' ", new String[]{mainId});
        contractMainDao.removeByCondition("AND id = ? ", new String[]{mainId});
        return true;
    }

    //作废
    @Override
    public Boolean obsolete(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = json.getString("id");
        String flag = json.getString("flag");
        if (null != flag && flag.equals("1")) {
            ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
            if (null == contractMainEntity) {
                return false;
            }
            contractMainEntity.setAuditFlag("3");
            contractMainDao.update(contractMainEntity);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public JSONObject selectContractAccountList(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String auditFlag = json.getString("auditFlag");
        String haveDelivery = json.getString("haveDelivery");
        String customerKey = json.getString("customerKey");
        String haveSettle = json.getString("haveSettle");
        String key = json.getString("key");
        String userId = json.getString("userId");
        String companyId = json.getString("companyId");
        StringBuilder condition = new StringBuilder();
        String companyIds = "";
        if (!StringUtils.isBlank(auditFlag)) {
            condition.append("AND t_con_main.AUDIT_FLAG='" + auditFlag + "'");
        }
        if (!StringUtils.isBlank(haveDelivery)) {
            condition.append("AND t_con_main.HAVE_DELIVERY ='" + haveDelivery + "'");
        }
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND t_con_main.BUYER LIKE '%" + key + "%' ");
        }
        String userIds = "";
        if (!StringUtils.isBlank(userId)) {
            userIds = checkDao.getChilderByUserId(userId, true);
            List<JSONObject> userMainList = userDao.getViewByUserId(" and id=? and main=1", new Object[]{userId});
            String manageFlag = userMainList.get(0).getString("manageFlag");
            String areaType = userMainList.get(0).getString("areaType");
            List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String selectCompanyId = userList.get(i).getString("companyId");
                    String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                    //如果有下级
                    if (!StringUtils.isBlank(ids)) {
                        //如果有多个下级
                        if (ids.indexOf(",") >= 0) {
                            String[] idsSplit = ids.split(",");
                            for (String id : idsSplit) {
                                companyIds += "'" + id + "',";
                            }
                        } else {
                            //如果只有一个下级
                            companyIds += "'" + ids + "',";
                        }
                    }
                    companyIds += "'" + selectCompanyId + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            } else {
                companyIds = "''";
            }
            if (manageFlag.equals("1") || areaType.equals("2") || areaType.equals("3")) {
                userIds = "";
            } else {
                companyIds = "";
            }
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(json.getString("pageSize"))) {
            pageSize = json.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(json.getString("requestPage"))) {
            requestPage = json.getInteger("requestPage");
        }
        if (!StringUtils.isBlank(haveSettle)) {
            condition.append(" AND t_con_main.HAVE_SETTLE =" + haveSettle + " \n");
        }
        if (!StringUtils.isBlank(customerKey)) {
            condition.append(" AND (t_con_main.BUYER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SERIAL_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SELLER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.CONTRACT_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BRAND_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.DEVICE_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.MODEL_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUYER_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUY_TYPE LIKE '%" + customerKey + "%' " +
                    "   or t_con_main.REGION_MANAGER_NAME LIKE '%" + customerKey + "%')\n");
        }

        if (!StringUtils.isBlank(companyIds)) {
            condition.append("AND (t_con_main.SELLER_COMPANY_ID IN (" + companyIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        if (!StringUtils.isBlank(companyId) && !companyId.equals("201712161613432EAF27DBCCB7D0E6CA")) {
            condition.append(" AND t_con_main.SELLER_COMPANY_ID = '" + companyId + "'\n");
        }
        if (!StringUtils.isBlank(userIds)) {
            condition.append("AND (t_con_main.REGION_MANAGER_ID IN (" + userIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        List<JSONObject> recordsList = contractMainDao.selectContractAccountList(condition.toString(), requestPage, pageSize);

        if (recordsList.size() > 0 && recordsList != null) {
            for (int i = 0; i < recordsList.size(); i++) {
                //添加到期日期到期金额
                JSONObject accountSubDate = new JSONObject();
                String type = "";
                accountSubDate = contractMainDao.getContractAccountSubDate(recordsList.get(i).getString("id"));
                if (accountSubDate != null) {
                    recordsList.get(i).put("accountSubDate", accountSubDate.getString("repayMent"));
                    type = accountSubDate.getString("type");
                    if (type.equals("2")) {
                        recordsList.get(i).put("accountSubMoney", accountSubDate.getString("contractRepayMentAmount"));
                    } else {
                        recordsList.get(i).put("accountSubMoney", accountSubDate.getString("total"));
                    }
                } else {
                    recordsList.get(i).put("accountSubDate", "");
                    recordsList.get(i).put("accountSubMoney", "");

                }
                //添加拼接款项
                List<JSONObject> accountType = new ArrayList<>();
                accountType = contractMainDao.getContractAccountType(recordsList.get(i).getString("id"));
                String kx = "";
                if (accountType != null && accountType.size() > 0) {
                    for (int j = 0; j < accountType.size(); j++) {
                        String kxType = "";
                        kxType = accountType.get(j).getString("type");
                        if (kxType.equals("3") || kxType.equals("1")) {
                            if (!kx.contains("首付款")) {
                                kx = kx + "首付款/";
                            }
                        } else if (kxType.equals("2") || kxType.equals("4")) {
                            if (!kx.contains("融资款")) {
                                kx = kx + "融资款/";
                            }
                        } else if (kxType.equals("0")) {
                            if (!kx.contains("分期款")) {
                                kx = kx + "分期款/";
                            }
                        }
                    }
                    if (!StringUtils.isBlank(kx)) {
                        recordsList.get(i).put("kx", kx.substring(0, kx.length() - 1));
                    } else {
                        recordsList.get(i).put("kx", "");
                    }
                } else {
                    recordsList.get(i).put("kx", "");

                }
            }
        }
        int recordCount = contractMainDao.selectContractAccountCount(condition.toString());
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", recordsList);
        return result;
    }

    @Override
    public List<JSONObject> getAllContractAccount(String userId, String customerKey, String auditFlag, String haveSettle, String selectCom, String haveDelivery) {
        StringBuilder condition = new StringBuilder();
        String companyIds = "";
        if (!StringUtils.isBlank(auditFlag)) {
            condition.append("AND t_con_main.AUDIT_FLAG='" + auditFlag + "'");
        }
        if (!StringUtils.isBlank(haveDelivery)) {
            condition.append("AND t_con_main.HAVE_DELIVERY ='" + haveDelivery + "'");
        }
        String userIds = "";
        if (!StringUtils.isBlank(userId)) {
            userIds = checkDao.getChilderByUserId(userId, true);
            List<JSONObject> userMainList = userDao.getViewByUserId(" and id=? and main=1", new Object[]{userId});
            String manageFlag = userMainList.get(0).getString("manageFlag");
            List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String selectCompanyId = userList.get(i).getString("companyId");
                    String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                    //如果有下级
                    if (!StringUtils.isBlank(ids)) {
                        //如果有多个下级
                        if (ids.indexOf(",") >= 0) {
                            String[] idsSplit = ids.split(",");
                            for (String id : idsSplit) {
                                companyIds += "'" + id + "',";
                            }
                        } else {
                            //如果只有一个下级
                            companyIds += "'" + ids + "',";
                        }
                    }
                    companyIds += "'" + selectCompanyId + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            } else {
                companyIds = "''";
            }
            if (manageFlag.equals("1")) {
                userIds = "";
            } else {
                companyIds = "";
            }
        }

        if (!StringUtils.isBlank(haveSettle)) {
            condition.append(" AND t_con_main.HAVE_SETTLE =" + haveSettle + " \n");
        }
        if (!StringUtils.isBlank(customerKey)) {
            condition.append(" AND (t_con_main.BUYER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SERIAL_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SELLER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.CONTRACT_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BRAND_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.DEVICE_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.MODEL_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUYER_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUY_TYPE LIKE '%" + customerKey + "%' " +
                    "   or t_con_main.REGION_MANAGER_NAME LIKE '%" + customerKey + "%')\n");
        }

        if (!StringUtils.isBlank(companyIds)) {
            condition.append("AND (t_con_main.SELLER_COMPANY_ID IN (" + companyIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        if (!StringUtils.isBlank(userIds)) {
            condition.append("AND (t_con_main.REGION_MANAGER_ID IN (" + userIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        List<JSONObject> recordsList = contractMainDao.getAllContractAccount(condition.toString());
        return recordsList;
    }

    @Override
    public JSONObject getSales0List(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = json.getString("dateTime");
        List<JSONObject> recordsList = contractMainDao.getSales0List(dateTime);
        //存放list
        JSONObject result = new JSONObject();
        result.put("records", recordsList);
        return result;
    }

    @Override
    public JSONObject selectSales0NewList(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = json.getString("companyId");
        String dateTime = json.getString("dateTime");
        StringBuilder condition = new StringBuilder();
        condition.append(" AND t_con_main.CONTRACT_TYPE = 1 ");
        if (!StringUtils.isBlank(dateTime)) {
            condition.append(" AND t_con_main.DELIVERY_DATE LIKE '%" + dateTime + "%' ");
        }
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" AND t_con_main.SELLER_COMPANY_ID = '" + companyId + "' ");
        }
        List<JSONObject> recordsList = contractMainDao.selectContractAccountList(condition.toString(), 1, Integer.MAX_VALUE);
        //存放list
        JSONObject result = new JSONObject();
        // 子数组对象
        result.put("records", recordsList);
        return result;
    }

    @Override
    public List<JSONObject> selectReceivable(String jsonData) {
        return contractMainDao.selectReceivable();
    }

    @Override
    public List<JSONObject> getContractBuyer(String jsonData) {
        JSONObject jsonObject = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String name = jsonObject.getString("key");
        StringBuffer sql = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!StringUtils.isBlank(name)) {
            sql.append(" WHERE t_con_main.BUYER LIKE ? ");
            sqlArgs.add("%" + name + "%");
        }
        return contractMainDao.getContractBuyer(sql.toString(), sqlArgs.toArray());
    }


    @Override
    public List<JSONObject> getRepaymentDate() {
        return repaymentDao.getRepaymentDate();
    }

    @Override
    public List<JSONObject> exportContractAccountList() {
        return contractMainDao.selectExportAccountList();
    }

    @Override
    public Boolean senderExpire() {
        contractMainDao.updateExpire();
        List<JSONObject> contractList = contractMainDao.senderExpire();
        if (contractList != null && contractList.size() > 0) {
            for (int i = 0; i < contractList.size(); i++) {
                JSONObject contract = contractList.get(i);
                ContractMainEntity entity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contract.getString("mainId"));
                if (entity.getHaveOverdue() != 1) {
                    entity.setHaveOverdue(2);
                    entity.setHaveOverdueNo(contract.getInteger("repaymentDate"));
                    contractMainDao.update(entity);
                }
            }
            return true;
        }
        return false;
    }

    //给客户发短信
    public static final String SENDER_CUS_REMIND = "%1s%2s您好，您购买的%3s%4s（%5s-%6s）月还款将于%7s到期，" +
            "请您按时还款。查看账单详情%8s" +
            "（如已还款，请忽略此短信。此短信内容仅供参考，不作为付款凭证。）";
    //给内部人员发短信
    public static final String SENDER_INNER_REMIND = "%1s%2s您好，您购买的%3s%4s（%5s-%6s）月还款将于%7s到期，" +
            "请您按时还款。 <a href='%8s'>点此查看账单</a>" +
            "（如已还款，请忽略此短信。此短信内容仅供参考，不作为付款凭证。）";

    @Override
    public Boolean senderMessage(String mainId) {
        String months = DateUtils.nowMouthByString(repaymentDao.getCurrentTime());
        JSONObject sender = new JSONObject();
        StringBuilder sb = new StringBuilder();
        sender = repaymentDao.getRepaymentSender(mainId);
        if (sender == null) {
            sender = repaymentDao.getRepaymentSender(mainId, months);
        }
        String customerName = sender.getString("customerName");
        String customerTel = sender.getString("customerTel");
        String brandName = sender.getString("brandName");
        String modelName = sender.getString("modelName");
        String buyerTaxNo = sender.getString("buyerTaxNo");
        String deviceName = sender.getString("deviceName");
        String repaymentDate = sender.getString("repaymentDate");
        String serialNo = sender.getString("serialNo");
        String regionManagerId = sender.getString("regionManagerId");
        String bigRegionManagerId = sender.getString("bigRegionManagerId");
        String regionalSupportId = sender.getString("regionalSupportId");
        String createUserId = sender.getString("createUserId");
        String creditManagerId = sender.getString("creditManagerId");
        String dataOfficerId = sender.getString("dataOfficerId");
        String takeOverManagerId = sender.getString("takeOverManagerId");
        if (StringUtils.isNotEmpty(regionManagerId)) {
            sb.append("|");
            sb.append(regionManagerId);
        }
        if (StringUtils.isNotEmpty(bigRegionManagerId)) {
            sb.append("|");
            sb.append(bigRegionManagerId);
        }
        if (StringUtils.isNotEmpty(regionalSupportId)) {
            sb.append("|");
            sb.append(regionalSupportId);
        }
        if (StringUtils.isNotEmpty(createUserId)) {
            sb.append("|");
            sb.append(createUserId);
        }
        if (StringUtils.isNotEmpty(creditManagerId)) {
            sb.append("|");
            sb.append(creditManagerId);
        }
        if (StringUtils.isNotEmpty(dataOfficerId)) {
            sb.append("|");
            sb.append(dataOfficerId);
        }
        if (StringUtils.isNotEmpty(takeOverManagerId)) {
            sb.append("|");
            sb.append(takeOverManagerId);
        }
        sb.append("|");
        sb.append("201712182044422D8254F02E0151637E");
        if (sb.length() > 0) {
            sb.deleteCharAt(0);
        }
        String httpHtml = "http://oa.yingfeng365.com/page/accountMessageNew.html?id=" + mainId + "";
        String url = "http://suo.im/api.php?format=json&url=";
        JSONObject dlRequest = HttpUtil.request(url + httpHtml,
                "GET", null);
        String ysHtml = dlRequest.getString("url");
        String sendName = matchesOdd(buyerTaxNo);
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", sb);
        msgObject.put("content", String.format(SENDER_INNER_REMIND, customerName, sendName, brandName,
                deviceName, modelName,
                serialNo, repaymentDate, ysHtml));
        tokenDao.sendTextMsg(msgObject.toJSONString());
        return true;
    }

    @Override
    public JSONObject getRepaymentSender(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject sender = new JSONObject();
        String months = DateUtils.nowMouthByString(repaymentDao.getCurrentTime());
        String maindId = jsonParams.getString("mainId");
        sender = repaymentDao.getRepaymentSender(maindId);
        if (sender == null) {
            sender = repaymentDao.getRepaymentSender(maindId, months);
        }
        String customerName = sender.getString("customerName");
        String customerTel = sender.getString("customerTel");
        String buyerTaxNo = sender.getString("buyerTaxNo");
        String brandName = sender.getString("brandName");
        String modelName = sender.getString("modelName");
        String deviceName = sender.getString("deviceName");
        String repaymentDate = sender.getString("repaymentDate");
        String serialNo = sender.getString("serialNo");
        String comName = "";
        String signName = "";
        String sendName = matchesOdd(buyerTaxNo);
        switch (sender.getString("companyName")) {
            case "黑龙江灜源":
                comName = SendConstant.SENDER_HLJ;
                signName = SendConstant.COMPANY_HLJ;
                break;
            case "吉林清源":
                comName = SendConstant.SENDER_JL;
                signName = SendConstant.COMPANY_JL;
                break;
            case "辽宁灜湖":
                comName = SendConstant.SENDER_LN;
                signName = SendConstant.COMPANY_LN;
                break;
            case "江苏滚滚向前":
                comName = SendConstant.SENDER_GGXQ;
                signName = SendConstant.COMPANY_GGXQ;
                break;
            case "安徽灜湖":
                comName = SendConstant.SENDER_AH;
                signName = SendConstant.COMPANY_AN;
                break;
            case "河北灜源":
                comName = SendConstant.SENDER_HB;
                signName = SendConstant.COMPANY_HB;
                break;
            case "甘肃&宁夏":
                comName = SendConstant.SENDER_GS;
                signName = SendConstant.COMPANY_GS;
                break;
            case "湖南清源":
                comName = SendConstant.SENDER_HN;
                signName = SendConstant.COMPANY_HN;
                break;
            default:
                break;
        }
  /*      String httpHtml = "http://oa.yingfeng365.com/page/accountMessageNew.html?id=" + maindId + "";
        String url = "http://dwz.cn/admin/create";
        JSONObject paramJsonObject=new JSONObject();
        paramJsonObject.put("URL", httpHtml);
        JSONObject dlRequest = HttpUtil.request(url,
                "POST",paramJsonObject.toJSONString() );
        String ysHtml = dlRequest.getString("ShortUrl");*/
        String httpHtml = "http://oa.yingfeng365.com/page/accountMessageNew.html?id=" + maindId + "";
        String url = "http://suo.im/api.php?format=json&url=";
        JSONObject dlRequest = HttpUtil.request(url + httpHtml,
                "GET", null);
        String ysHtml = dlRequest.getString("url");
        String content = String.format(SENDER_CUS_REMIND,
                customerName, sendName, brandName,
                deviceName, modelName,
                serialNo, repaymentDate, ysHtml);
        JSONObject repaymentMoney = repaymentDao.getRepaymentAmount(repaymentDate, maindId);
        List<JSONObject> repaymentList = repaymentDao.getRepaymentHistory(maindId);
        JSONObject result = new JSONObject();
        result.put("customerTel", customerTel);
        result.put("content", content);
        result.put("signName", signName);
        result.put("comName", comName);
        result.put("sender", sender);
        result.put("repaymentMoney", repaymentMoney);
        result.put("repaymentList", repaymentList);
        return result;
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }

    //标记消息为已读 /0-审核人 /2-申请人 /1-抄送人
    private void messageReceiverRead(String mainId, Integer userType) {
        StringBuffer sb = new StringBuffer();
        List<String> arg = new ArrayList<>();
        if (!org.apache.commons.lang3.StringUtils.isBlank(mainId)) {
            sb.append("AND mainId=?");
            arg.add(mainId);
        }
        if (null != userType) {
            sb.append("AND receiverUserType=?");
            arg.add(userType.toString());
        }
        String receiverIds = "";
        List<JSONObject> jsonObjectList = messageDao.getViewJSONListByCondition(sb.toString(), arg.toArray());
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (int i = 0; i < jsonObjectList.size(); i++) {
                receiverIds += "'" + jsonObjectList.get(i).getString("receiverId") + "',";
            }
        }
        if (receiverIds.length() > 1) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = null;
        }
        if (!org.apache.commons.lang3.StringUtils.isBlank(receiverIds)) {
            messageReceiverDao.updateReadFlag("T_SYS_MESSAGE_RECEIVER", "AND ID IN (" + receiverIds + ")");
        }
    }

    public static int between_days(String a, String b) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 自定义时间格式

        Calendar calendar_a = Calendar.getInstance();// 获取日历对象
        Calendar calendar_b = Calendar.getInstance();

        Date date_a = null;
        Date date_b = null;

        try {
            date_a = simpleDateFormat.parse(a);//字符串转Date
            date_b = simpleDateFormat.parse(b);
            calendar_a.setTime(date_a);// 设置日历
            calendar_b.setTime(date_b);
        } catch (ParseException e) {
            e.printStackTrace();//格式化异常
        }

        long time_a = calendar_a.getTimeInMillis();
        long time_b = calendar_b.getTimeInMillis();

        long between_days = (time_b - time_a) / (1000 * 3600 * 24);//计算相差天数
        return Integer.parseInt(String.valueOf(between_days));
    }

    private void sendResignationMessage(ContractMainEntity contractMainEntity, List<JSONObject> jsonObjectList) {
        List<String> userList = new ArrayList();
        String sjzyId = contractMainEntity.getDataOfficerId();//数据专员
        userList.add(contractMainEntity.getBigRegionManagerId());
        userList.add("大区经理");
        userList.add(contractMainEntity.getBigRegionManagerName());
        userList.add(contractMainEntity.getRegionalSupportId());
        userList.add("区域支持");
        userList.add(contractMainEntity.getRegionalSupportName());
        userList.add(contractMainEntity.getTakeOverManagerId());
        userList.add("接管区域经理");
        userList.add(contractMainEntity.getTakeOverManager());
        //删除之前的消息
        messageReceiverRead(contractMainEntity.getId(), -1);
        for (int i = 0; i < userList.size(); ) {
            if (!StringUtils.isBlank(userList.get(i))) {
                UserEntity userEntity = userDao.getById(userList.get(i));
                if (userEntity.getJobState() == 1) {

                    //企业号:给第一审核人发送消息
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", sjzyId);
                    msgObject.put("content", String.format(RESIGNATION_YSTZ,
                            userList.get(i + 1), userList.get(i + 2),
                            DateUtils.parse(messageDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                    ));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(sjzyId);
                    messageEntity.setCreateTime(messageDao.getCurrentTime());
                    messageEntity.setContent(String.format(RESIGNATION_YSTZ,
                            userList.get(i + 1), userList.get(i + 2),
                            DateUtils.parse(messageDao.getCurrentTime(), "yyyy-MM-dd HH:mm")
                    ));
                    messageEntity.setMessageType(0);//1审核 0通知
                    messageEntity.setMainId(contractMainEntity.getId());
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/apply/accountReceivable/detail.html?id=" + contractMainEntity.getId() + "&pageType=applyAudit&openType=dialog");
                    messageEntity.setOpenTitle(String.format(RESIGNATION_YSTZ_MESSAGE, userList.get(i + 1), userList.get(i + 2)));
                    messageDao.add(messageEntity);

                    //保存第一审核人信息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(sjzyId);
                    messageReceiverEntity.setUserType(-1);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                }
            }
            i += 3;
        }
    }

    @Override
    public JSONObject selectContractSalesList(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String auditFlag = json.getString("auditFlag");
        String haveDelivery = json.getString("haveDelivery");
        String customerKey = json.getString("customerKey");
        String haveSettle = json.getString("haveSettle");
        String selectCom = json.getString("selectCom");
        String key = json.getString("key");
        String userId = json.getString("userId");
        String companyId = json.getString("companyId");
        StringBuilder condition = new StringBuilder();
        String companyIds = "";
        if (!StringUtils.isBlank(auditFlag)) {
            condition.append("AND t_con_main.AUDIT_FLAG='" + auditFlag + "'");
        }
        if (!StringUtils.isBlank(haveDelivery)) {
            condition.append("AND t_con_main.HAVE_DELIVERY ='" + haveDelivery + "'");
        }
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND t_con_main.BUYER LIKE '%" + key + "%' ");
        }
        String userIds = "";
        if (!StringUtils.isBlank(userId)) {
            userIds = checkDao.getChilderByUserId(userId, true);
            List<JSONObject> userMainList = userDao.getViewByUserId(" and id=? and main=1", new Object[]{userId});
            String manageFlag = userMainList.get(0).getString("manageFlag");
            String areaType = userMainList.get(0).getString("areaType");
            List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String selectCompanyId = userList.get(i).getString("companyId");
                    String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                    //如果有下级
                    if (!StringUtils.isBlank(ids)) {
                        //如果有多个下级
                        if (ids.indexOf(",") >= 0) {
                            String[] idsSplit = ids.split(",");
                            for (String id : idsSplit) {
                                companyIds += "'" + id + "',";
                            }
                        } else {
                            //如果只有一个下级
                            companyIds += "'" + ids + "',";
                        }
                    }
                    companyIds += "'" + selectCompanyId + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            } else {
                companyIds = "''";
            }
            if (manageFlag.equals("1") || areaType.equals("2") || areaType.equals("3")) {
                userIds = "";
            } else {
                companyIds = "";
            }
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(json.getString("pageSize"))) {
            pageSize = json.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(json.getString("requestPage"))) {
            requestPage = json.getInteger("requestPage");
        }
        if (!StringUtils.isBlank(haveSettle)) {
            condition.append(" AND t_con_main.HAVE_SETTLE =" + haveSettle + " \n");
        }
        if (!StringUtils.isBlank(selectCom) && !"请选择公司".equals(selectCom)) {
            condition.append(" AND t_con_main.SELLER LIKE '%" + selectCom + "%'");
        }
        if (!StringUtils.isBlank(customerKey)) {
            condition.append(" AND (t_con_main.BUYER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SERIAL_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SELLER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.CONTRACT_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BRAND_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.DEVICE_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.MODEL_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUYER_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUY_TYPE LIKE '%" + customerKey + "%' " +
                    "   or t_con_main.REGION_MANAGER_NAME LIKE '%" + customerKey + "%')\n");
        }

        if (!StringUtils.isBlank(companyIds)) {
            condition.append("AND (t_con_main.SELLER_COMPANY_ID IN (" + companyIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        if (!StringUtils.isBlank(companyId) && !companyId.equals("201712161613432EAF27DBCCB7D0E6CA")) {
            condition.append(" AND t_con_main.SELLER_COMPANY_ID = '" + companyId + "'\n");
        }
        if (!StringUtils.isBlank(userIds)) {
            condition.append("AND (t_con_main.REGION_MANAGER_ID IN (" + userIds + ") \n" +
                    "OR t_con_main.TAKE_OVER_MANAGER IN (" + userIds + ") \n" +
                    "AND t_con_main.AUDIT_FLAG='1')\n");
        }
        List<JSONObject> recordsList = contractMainDao.selectContractSalesList(condition.toString(), requestPage, pageSize);
        int recordCount = contractMainDao.selectContractSalesList(condition.toString());
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", recordsList);
        return result;
    }

    public JSONObject getAllManagerId(List<JSONObject> Json, String companyId, String roleName) {
        String managerId = "";
        String managerName = "";
        String mainRoleName = "";
        int isAll = 0;
        if (Json.size() > 1) { //有多个
            for (JSONObject json : Json) {
                if (regionAchivementsDao.getMainRoleNameByUserId(json.getString("userId"), companyId, roleName) != null) {
                    isAll = 1;
                    //说明是主职位
                    managerId = json.getString("userId");
                    managerName = json.getString("userName");
                }
            }
            if (isAll == 0) {//说明全都是兼职
                managerId = Json.get(0).getString("userId");
                managerName = Json.get(0).getString("userName");
            }
        } else {
            managerId = Json.get(0).getString("userId");
            managerName = Json.get(0).getString("userName");
        }
        JSONObject info = new JSONObject();
        info.put("managerId", managerId);
        info.put("managerName", managerName);
        return info;
    }
}
